3

I am using NodeJS for this. I have a configuration.js module which I use in 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();

Of course this throws an error since this.dataPath is undefined. My question is why is this an empty object. What I am expecting is that this inside the getLogPath function refers to spctrConfiguration object. Since the function getLogPath was called from spctrConfiguration in index.js. Any help is much appreciated!

mrQWERTY
  • 3,389
  • 9
  • 34
  • 83
  • 1
    Along with the duplicate, since arrow functions don't bind `this` like normal function expressions do, you get the global `this`, which in the browser is `window`. But with NodeJS, there is no window, so it points to actual current module object. – Andrew Li Jan 07 '18 at 07:07
  • `spctrConfiguration.getLogPath=()={console.log(spctrConfiguration)` That should quickly fix your current problem. Best is to avoid using `this` in JavaScript and use [functions returning objects](https://gist.github.com/mpj/17d8d73275bca303e8d2) if you have multiple instances. You have only one instance so no need for that. – HMR Jan 07 '18 at 09:03

0 Answers0