I have a JavaScript file which is loaded by require.
// loaded by require()
var a = this; // \"this\" is an empty object
this.anObject = {name:
In Javascript the value of this is determined when a function is called. Not when a function is created. In nodeJS in the outermost scope of a module the value of this is the current module.exports object. When a function is called as a property of an object the value of this changes to the object it was called. You can remember this simply by the left-of-the-dot rule:
When a function is called you can determine the value of
thisby looking at the place of the function invocation. The object left of the dot is the value ofthis. If there is no object left of the dot the value ofthisis themodule.exportsobject (windowin browsers).
caveats:
es2015 arrow function which don't have their own binding of this.call, apply, and bind can bend the rules regarding the this value.console.log(this); // {} , this === module.exports which is an empty object for now
module.exports.foo = 5;
console.log(this); // { foo:5 }
let obj = {
func1: function () { console.log(this); },
func2: () => { console.log(this); }
}
obj.func1(); // obj is left of the dot, so this is obj
obj.func2(); // arrow function don't have their own this
// binding, so this is module.exports, which is{ foo:5 }
Output: