what's the out of this example? and explain why
const obj = {x: 1, y: 2};
obj.fn1 = function () {
this.x = 10;
return function () {
this.x = 100;
};
};
obj.fn2 = function () {
this.y = 20;
return function () {
this.y = 200;
};
};
const fn1 = obj.fn1();
const fn2 = obj.fn2;
fn1();
fn2()();
console.log(obj.x, obj.y);
the output is 10 and 2
why?
because in the first example we called fn1
directly, so this
inside the function will refer to the obj
but in the second example we copied the method to a global variable fn2, so when we executed it this
will refer to the window object(or global if using node) so the obj
value will be still 2
and the nested function will always be executed in the window object context
so if we added console.log(globalThis.x, globalThis.y);
at the end it will print to us 100 and 200