Value Of This Inside Object Method?
I very confusing about the value of this at the moment of an invocation function using arrow functions. Let's take my example: var obj = { property: 5, func1: function () {
Solution 1:
So, why the value of this inside
func2
is not inheriting the value of his enclosing scopeobj
?
The obj
here is not the "enclosing" scope. The scope that you are defining the obj
in is the "enclosing" scope.
Consider this example:
var obj = {
property: 5,
func1: function () {
letfunc2 = () => {
console.log(this.property);
}
func2();
},
}
obj.func1(); // logs 5
obj.func1.call({
property: 6
}) // logs 6
When the inner func2
is called, the this
keyword refers to the obj
as this
in the wrapper func1
function refers to the obj
and the func2
inherits the this
value. The inner arrow function does not bind it's own this
value.
Solution 2:
The this
in func2
is inheriting the value of the scope of the function itself, no more. To make it work, you'll have to make something like that :
var obj = {
property: 5,
func1: function () {
console.log(this.property); // shows 5
},
func2: () => {
console.log(this.property); // shows undefinedthis.property = 6;
console.log(this.property); // shows 6
}
}
Post a Comment for "Value Of This Inside Object Method?"