Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 819
Kirollos Nasr Avatar asked Jan 19 '20 12:01

Kirollos Nasr


People also ask

What does get () do in JavaScript?

The get keyword will bind an object property to a function. When this property is looked up now the getter function is called. The return value of the getter function then determines which property is returned.

What is the this keyword in JavaScript?

In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object. Alone, this refers to the global object.

What is a getter function?

The getter function is used to retrieve the variable value and the setter function is used to set the variable value. Remember: You can directly access public member variables, but private member variables are not accessible. Therefore, we need getter functions.

What is this in a function?

“this” inside FunctionsThe value of this inside a function is usually defined by the function's call. So, this can have different values inside it for each execution of the function. In your index. js file, write a very simple function that simply checks if this is equal to the global object.


1 Answers

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.

like image 76
T.J. Crowder Avatar answered Sep 20 '22 17:09

T.J. Crowder