Search code examples
javascriptgetter-setter

The value of `this` keyword of a function returned from a getter


I found an unexpected value of this keyword in the following example :

let x = {
    z : 10 ,
    get func1() {
        return function(v) {
            console.log(this === v);
        }
    }
}


x.func1(x)

The value of this keyword is the object x as if it's executed from that object, I expect only the get function that has this keyword equals to the calling object x

this example shows us the difference

let x = {
    func2() {
        return function(v) {
            console.log(this === v);
        }
    }
}

x.func2()(x);

In both examples func1 which is the getter function, and func2 which is a method of the object, are executed from the object x, and the returned function is then executed. So why this value in the first example not equals to the global object instead of the object x.


Solution

  • That's a very interesting question.

    It's because the function is being called immediately on the result of a property access. So these are fundamentally equivalent:

    let x = {
        get func1() {
            return function(v) {
                console.log(this === v);
            };
        },
        func2(v) {
            console.log(this === v);
        }
    };
    
    x.func1(x);
    x.func2(x);

    In both cases:

    1. The value of the property is read, resulting in a function reference.
    2. That function is executed as part of the same property access expression.

    The fact that func1 is an accessor property and func2 is a data property doesn't matter. It's how the value resulting from reading the property is used that matters.