3

I made some search around but wasn't able to find the exact answer for:

this.age = 20;

var getAge = function () {
    return this.age;
};

var person = {
    age: 30,
    getAge: getAge
};

console.log(this.age); // 20
console.log(getAge()); // undefined
console.log(person.getAge()); // 30

Why, in Node.js, the "this", when used inside the getAge function in the code, is undefined, if it is actually defined?

Considering only the language, it should work?

I know that:

console.log(this === exports);
console.log(this === module.exports);

Notice that in Chrome, it works and the getAge(), when executed, return 20.

Rodrigo Branas
  • 498
  • 5
  • 9
  • Try doing `var self = this;` at the top of your function, and then have getAge() return self.age instead. It's a common workaround for "this" weirdness in JS. – MarkNFI Mar 25 '16 at 14:13
  • @Quentin I think there's a node specificity here. `this` isn't the root object. – Denys Séguret Mar 25 '16 at 14:13
  • @Quentin My question was regarding the behavior of "this", inside a function, in Node.js, not the language. The question that you pointed is far more broad... – Rodrigo Branas Mar 25 '16 at 14:14
  • Thanks guys, I know how to solve it, I just want to understand the exact behavior of "this", inside a function in Node.js in that situation. – Rodrigo Branas Mar 25 '16 at 14:16
  • 1
    @apsillers The same code in a browser wouldn't log undefined here. – Denys Séguret Mar 25 '16 at 14:18
  • @apsillers that works in the browser, did not work in Node.js, just wondering to know more details around it. – Rodrigo Branas Mar 25 '16 at 14:20
  • @RodrigoBranas `Why, in Node.js, the "this", when used inside the getAge function in the code, is undefined, if it is actually defined?` actually `this.age` is. but still `this` has a defined value – Adnan Umer Mar 25 '16 at 14:30
  • @AdnanUmer I did not get your point... – Rodrigo Branas Mar 25 '16 at 15:51
  • It seems the same behavior when the Strict Mode is used, when "this" is set to undefined inside functions to avoid mistakes when using constructor function without new – Rodrigo Branas Mar 25 '16 at 16:36

0 Answers0