gpt4 book ai didi

javascript - 为什么 DOM 事件处理程序中的嵌套函数会修复 'this' 绑定(bind)

转载 作者:行者123 更新时间:2023-11-30 05:42:23 25 4
gpt4 key购买 nike

一个简单的问题,我还没找到答案。如果我处理将方法传递给 DOM 事件处理程序,this 引用 DOM 元素:

$('#foo').click(shapeA.describe);

而如果我将它包装在一个函数中,它会引用父对象(即您最常想要的效果):

$('#foo').click(function() { shapeA.describe(); });

我知道我可以使用各种技术,例如 bind 来确保可预测的行为。但我想了解上面两行之间的区别。

我找到了一篇文章 'Understanding the this keyword' ,其中指出:

If we call a function as a property of an object using either dot (i.e., obj.foo()) or bracket (i.e., obj“foo”) notation, this will refer to the parent object in the body of the function

这无法解释这种行为。这篇文章可能不正确,但它是迄今为止我发现的最好的文章!

那么,任何人都可以在与“this”相关的规则的上下文中解释这种行为吗?

如果需要,这里有一个 fiddle http://jsfiddle.net/PcLF3/

最佳答案

在这段代码中:

$('#foo').click(shapeA.describe);

您传递的是 click函数describe方法 没有 shapeA shapeA.describe就是您引用 describe 的方式.里面的代码click不知道 describe来自shapeA对象,它将在当前 DOM 上下文中被调用。

在你的第二种情况下,this匿名函数内部是当前的 DOM 对象。

$('#foo').click(function() { 
console.log(this);// `this` here refers to the current DOM object
shapeA.describe();
});

但是thisdescribe里面将是 shapeA正如您使用点符号调用它:shapeA.describe();

关于javascript - 为什么 DOM 事件处理程序中的嵌套函数会修复 'this' 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20028418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com