interview community logo

0
0
function scope coding test
1 answer

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);
JavaScript Robert Isaac asked 1 year ago


0

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

Robert Isaac answered 1 year ago loading comments...