I’m busy trying to understand the behaviour of the this
keyword by reading up about it on mdn web docs.
I made the following code snippet to explore the this
keyword behaviour, especially around arrow functions:
const arrow = () => this;
let y = {
name: 'object',
f1() { return this }, // y object
f2: () => { return this }, // global
f3() { return arrow() }, // global
f4() { return (() => this)() }, // y object
f5() { // global
function foobar () {
return this;
}
return foobar();
},
f6() { // undefined
function foobar () {
'use strict';
return this;
}
return foobar();
},
};
this.name = 'global';
console.log(globalThis) // global
console.log(this); // global
console.log(y.f1()); // object
console.log(y.f2()); // global
console.log(y.f3()); // global
console.log(y.f4()); // object
console.log(y.f5()); // global
console.log(y.f6()); // undefined
When executing the above code from within Chrome v120 everything behaves as expected, where the global object is the Window.
When executing the code with node v18.17.1 the y.f5()
method yields the following:
<ref *1> Object [global] {
global: [Circular *1],
queueMicrotask: [Function: queueMicrotask],
clearImmediate: [Function: clearImmediate],
setImmediate: [Function: setImmediate] {
[Symbol(nodejs.util.promisify.custom)]: [Getter]
},
structuredClone: [Function: structuredClone],
clearInterval: [Function: clearInterval],
clearTimeout: [Function: clearTimeout],
setInterval: [Function: setInterval],
setTimeout: [Function: setTimeout] {
[Symbol(nodejs.util.promisify.custom)]: [Getter]
},
atob: [Function: atob],
btoa: [Function: btoa],
performance: Performance {
nodeTiming: PerformanceNodeTiming {
name: 'node',
entryType: 'node',
startTime: 0,
duration: 23.78549998998642,
nodeStart: 1.4962089955806732,
v8Start: 4.412084013223648,
bootstrapComplete: 16.266708999872208,
environment: 9.128708988428116,
loopStart: -1,
loopExit: -1,
idleTime: 0
},
timeOrigin: 1703311964946.281
},
fetch: [AsyncFunction: fetch]
}
Why is this?