Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/459.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript函数属性';s此关键字返回空对象_Javascript_Node.js_This - Fatal编程技术网

Javascript函数属性';s此关键字返回空对象

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调用的。非常感谢您的帮助 除了复制之外,由于箭头函数不像普通函数表达式

我正在为此使用NodeJS。我在index.js中使用了一个configuration.js模块

configuration.js

index.js

当然,这会抛出一个错误,因为
这个.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();