我应该如何看待对象字面量中的 属性 定义?
How should I think of property definitions in object literals?
let o = {
x: 1,
foo() {
setTimeout(()=>
console.log(this.x),
100);
}
}
o.foo();
这会在 100 毫秒后打印出 1。
这是不是因为它等价于下面的意思,意味着箭头函数的词法 this
绑定有效?
let o = new (function Object() {
this.x = 1;
this.foo = ()=> console.log(this.x);
});
o.foo();
Is this because it is equivalent to the following, meaning that the lexical this binding of arrow functions works?
不,它比那简单得多。相当于
var o = {
x: 1,
foo: function() {
setTimeout(()=>
console.log(this.x),
100);
}
};
o.foo();
并转换为箭头函数:
var o = {
x: 1,
foo: function() {
var self = this;
setTimeout(function() {
console.log(self.x)
}, 100);
}
};
o.foo();
由于您正在调用 o.foo()
,因此 foo
中的 this
指的是 o
。因为箭头函数的 this
受词法作用域限制,所以它访问 foo
的 this
.
let o = {
x: 1,
foo() {
setTimeout(()=>
console.log(this.x),
100);
}
}
o.foo();
这会在 100 毫秒后打印出 1。
这是不是因为它等价于下面的意思,意味着箭头函数的词法 this
绑定有效?
let o = new (function Object() {
this.x = 1;
this.foo = ()=> console.log(this.x);
});
o.foo();
Is this because it is equivalent to the following, meaning that the lexical this binding of arrow functions works?
不,它比那简单得多。相当于
var o = {
x: 1,
foo: function() {
setTimeout(()=>
console.log(this.x),
100);
}
};
o.foo();
并转换为箭头函数:
var o = {
x: 1,
foo: function() {
var self = this;
setTimeout(function() {
console.log(self.x)
}, 100);
}
};
o.foo();
由于您正在调用 o.foo()
,因此 foo
中的 this
指的是 o
。因为箭头函数的 this
受词法作用域限制,所以它访问 foo
的 this
.