Javascript函数属性';s此关键字返回空对象
我正在为此使用NodeJS。我在index.js中使用了一个configuration.js模块 configuration.js index.js 当然,这会抛出一个错误,因为Javascript函数属性';s此关键字返回空对象,javascript,node.js,this,Javascript,Node.js,This,我正在为此使用NodeJS。我在index.js中使用了一个configuration.js模块 configuration.js index.js 当然,这会抛出一个错误,因为这个.dataPath是未定义的。 我的问题是为什么这个是一个空对象。 我期望的是getLogPath函数中的this引用spctrConfiguration对象。因为函数getLogPath是从index.js中的spctrConfiguration调用的。非常感谢您的帮助 除了复制之外,由于箭头函数不像普通函数表达式
这个.dataPath
是未定义的。
我的问题是为什么这个是一个空对象。
我期望的是getLogPath
函数中的this
引用spctrConfiguration
对象。因为函数getLogPath
是从index.js
中的spctrConfiguration
调用的。非常感谢您的帮助 除了复制之外,由于箭头函数不像普通函数表达式那样绑定this
,因此可以得到全局this
,它在浏览器中是窗口
。但是对于NodeJS,没有窗口,所以它指向实际的当前模块对象。spctrConfiguration.getLogPath=()={console.log(spctrConfiguration)
这应该可以很快解决您当前的问题。最好是避免在JavaScript中使用这个
,如果您有多个实例,就使用它。您只有一个实例,所以不需要这样做。
let spctrConfiguration = {
dataPath: '/data/',
mongoDB: 'datadb',
mongoHost: 'mongo',
mongoPort: 27017,
redisHost: 'redis',
redisPort: 6379,
getLogPath: () => {
console.log(this); //this is {}
return path.join(this.dataPath, 'spctrworker_logs');
},
getHtmlPath: () => {
return path.join(this.dataPath, 'spctrworker_html');
}
};
if (process.env.SPCTR_MODE == 'DEVELOPMENT') {
spctrConfiguration.dataPath = __dirname + '/dev_data/';
spctrConfiguration.mongoHost = '127.0.0.1';
spctrConfiguration.redisHost = '127.0.0.1';
}
module.exports = spctrConfiguration;
let spctrConfiguration = require('./config/configuration');
let app = express();
let logPath = spctrConfiguration.getLogPath();
let htmlPath = spctrConfiguration.getHtmlPath();