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(...)