I'm trying to set this
in various scenarios.
The following code executed in node.js v6.8.1
will print what is commented at the end of each line:
function requireFromString(src) {
var Module = module.constructor;
var m = new Module();
m._compile(src, __filename);
return m.exports;
}
(function(){
var f1 = (() => {console.log(this.a === 1)});
var f2 = function(){ console.log(this.a === 1) };
var f3 = requireFromString('module.exports = (() => {console.log(this.a === 1)});');
var f4 = requireFromString('module.exports = function(){ console.log(this.a === 1) };');
console.log('Body:');
console.log(this.a === 1); // true
(()=>console.log(this.a === 1))(); // true
(()=>console.log(this.a === 1)).call(this); // true
(function(){console.log(this.a === 1)})(); // false
(function(){console.log(this.a === 1)}).call(this); // true
console.log('\nFunctions:');
f1(); // true
f1.call(this); // true
f2(); // false
f2.call(this); // true
f3(); // false [1]
f3.call(this); // false [2]
f4(); // false
f4.call(this); // true
}).apply({a:1});
With the documentation for this and arrow functions I can explain all cases except the ones labelled with [1]
and [2]
.
Can somebody shed some light on the observed behaviour? And maybe give a hint how I can call f3
so that the function prints true.
Notes
- The
requireFromString
-function is adapted from Load node.js module from string in memory and is just a hack to slim down this stackoverflow question. In practice this is replaced by an ordinaryrequire(...)
this
from the lexical context. If that's not what you want, then don't use an arrow function. If you want to "set" or "control" the value ofthis
, then use a regular function call and one of the various methods available (.apply()
,.call()
,obj.method()
, etc...) for controlling the value ofthis
in that function call.f4();
and thef4.call(this);
?this
for the 'matcher' no matter what kind of function is provided.this
version.