(Stack Overflow 通知我这个问题可能会被否决或标记为重复,但我建议您不要这样做,因为我一直在仔细研究 Stack Overflow 的答案并尝试回答它,并且发现帖子说的是相互矛盾的事情,这就是我正在努力解决的问题)。
我试图理解箭头函数的绑定(bind)(以及它与它们作为对象和类方法的使用有何关系)。我的理解是,箭头函数在创建时绑定(bind),从定义它的上下文中获取 this 。有的帖子说是这样的。有些帖子的说法相反,认为箭头函数根本没有绑定(bind),例如这篇文章,Arrow Functions and This ,其中得票最高的答案是:
Short answer: this points at the nearest bound this - in the code provided this is found in the enclosing scope.
Longer answer: Arrow functions
bind their this when they are createddo not have this, arguments or other special names bound at all - when the object is being created the name this is found in the enclosing scope, not the person object.
我创建了一个小Codepen示例来测试哪个是正确的,我相信箭头函数在创建时确实是永久绑定(bind)的:如果将箭头函数分配给对象的属性,然后在另一个对象的上下文中调用该函数,它仍然保留 this
它在创建时就有。
是哪一个?箭头函数在创建时是否永久绑定(bind)到创建它们的上下文的 this
,还是根本不绑定(bind)?
如果它们在创建时确实绑定(bind)了,这就是您可以在 ES6 类中使用箭头函数作为方法的原因吗?也就是说本例中
class MyClass {
constructor() {
this.myVariable = 0;
console.log("in constructor this is",this)
this.myMethod = () => {
console.log("in myMethod this is",this)
this.myVariable++;
};
}
箭头函数 myMethod 只是绑定(bind)到构造函数已定义为正在创建的实例的上下文的 this
?
感谢您的帮助!
最佳答案
实际上两者说的是相同的,而“this
is found in the enclosurescope”在技术上可能更正确。这里重要的是“范围”是按词法确定的,因此如何以及在何处调用该函数并不重要,重要的是它是否被声明:
const a = () => this; // global scope
function b() {
const c = () => this; // function scope of b
}
可以说,作用域在声明时就绑定(bind)到函数,并且由于作用域还包含上下文 (this
),因此上下文 (this
)也被绑定(bind)。
如果我们想象 this
是一个常规变量,也许整个概念会变得更加清晰:
const this = window;
const a = () => this; // global scope, "this" is window
function b(this) { // context determined on call
const c = () => this; // scope of the b function
}
关于javascript - Javascript 箭头函数是在创建时永久绑定(bind)还是根本不绑定(bind) : the case of object and class methods,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51458318/