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.
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.
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.
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.
“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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With