问题
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 () {
console.log(this.property);
},
func2: () => {
console.log(this.property);
}
}
When i put this code on the browser console, an interesting thing happens, func1()
will output 5
as expected *, but when i run func2
i got undefined
. What is going on here? Why the value of this
inside func2
makes reference to the global object(Window
in this case).
I think i expect that output, because it is how it works, thats the reason why Alan and slevetman explains here and here respectively. But according to the Jason's explanation
Arrow functions do not have their own this value. The value of this inside an arrow function is always inherited from the enclosing scope.
So, why the value of this inside func2
is not inheriting the value of his enclosing scope obj
?
回答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 () {
let func2 = () => {
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.
回答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 undefined
this.property = 6;
console.log(this.property); // shows 6
}
}
来源:https://stackoverflow.com/questions/38557764/value-of-this-inside-object-method