This problem seems to be committed by many people, but I still don’t know enough about this
Let's record this problem now.
obj = {
a: 123,
b: this.a,
c: function () {
return this.a;
}
};
console.log(obj.b); // undefined
console.log(obj.c()); // 123
To put it simply, this is a problem of scope b
. The this in the attribute actually points to the parent scope, here is window, and we did not define the variable a in the window. The this in the c attribute points to obj, which is Because the object itself cannot create a scope, but functions (methods) can create a local scope.
1. Next we first add a to the window, the results are as follows
var a = 5
obj = {
a: 123,
b: this.a,
c: function () {
return this.a;
}
};
console.log(obj.b); // 5
console.log(obj.c()); // 123
2. If you really want to get a in b, then use the same writing as c
obj = {
a: 123,
b: function () {
return this.a;
},
c: function () {
return this.a;
}
};
console.log(obj.b()); // 123
console.log(obj.c()); // 123
3. Next we will try to change the this of b to obj
obj = {
a: 123,
b: obj.a,
};
console.log(obj.b);
Sure enough, an error was reported.
4. Then we change the this of c to obj
obj = {
a: 123,
c: function () {
return obj.a;
}
};
console.log(obj.c()); // 123
As expected, it can be output normally.
5. Finally, we use the arrow function to write the method. It is known that the arrow function without its own this will inherit the parent scope, which is window
obj = {
a: 123,
c: ()=>{
return this.a
}
};
console.log(obj.c()); // undefined
summary:
1. The object in the global environment is the same as the function in the global environment, this points to window
2. When called as an object method, this points to the object that called the method
3. The arrow function does not have its own this, it is still equivalent to a global object, and it still points to the window