Javascript函数属性< s关键字返回空对象

时间:2018-01-07 07:02:03

标签: javascript node.js this

我正在使用NodeJS。我有一个 configuration.js 模块,我在 index.js 中使用。

configuration.js

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;

index.js

let spctrConfiguration = require('./config/configuration');

let app = express();
let logPath = spctrConfiguration.getLogPath();
let htmlPath = spctrConfiguration.getHtmlPath();

当然,由于this.dataPath 未定义,因此会引发错误。 我的问题是为什么this是一个空对象。 我期待的是this函数中的getLogPath引用spctrConfiguration对象。由于函数getLogPath是从spctrConfiguration中的index.js调用的。非常感谢任何帮助!

0 个答案:

没有答案
相关问题