gpt4 book ai didi

javascript - 使用 jQuery 在 JavaScript 对象中使用 'this'

转载 作者:行者123 更新时间:2023-11-30 10:48:54 25 4
gpt4 key购买 nike

最近我一直在尝试使用以下结构在 JavaScript 中创建一个对象:

function colorDiv(div){
this.div=div;
this.div.bind("click",this.changeColor)
this.changeColor(){
this.div.css("background", "#FF0000");
}
}

问题是 changeColor 方法不能从 jQuery 环境中调用,因为 this 必须引用当前的 colorDiv 对象,所以绑定(bind)方法无法按预期工作。如何解决?

最佳答案

有几种方法。最简单的如下:

function ColorDiv(div) {
var that = this;

that.div = div;
that.div.bind("click", that.changeColor);

that.changeColor = function () {
that.div.css("background", "#FF0000");
};
}

var colorDiv = new ColorDiv($("#my-div"));
$("#something-else").click(colorDiv.changeColor);

您将对 this 的引用保存在变量 that 中,这正是 JavaScript 世界中用于此目的的常用名称。然后在 changeColor 方法中引用 that 而不是 this 。 (请注意,我在所有地方都使用了 that,只是为了保持一致性,尽管它真正有所不同的唯一地方是在 changeColor 方法中。)


另一个是使用Function#bind方法。您可以在每次调用 changeColor 时使用它,如下所示:

var colorDiv = new ColorDiv($("#my-div"));
$("#something-else").click(colorDiv.changeColor.bind(colorDiv));

或者您可以在 ColorDiv 类中使用它来确保所有方法在调用时都被正确绑定(bind):

this.changeColor = (function () {
this.div.css("background", "#FF0000");
}).bind(this);

如链接文章中所述,并非所有浏览器都支持 Function#bind,因此您需要像他们提供的那样的垫片,或者可能是 full-fledged ES5 shim。 .

Underscore.js 有一个 bindAll在这里也很有用的函数,尤其是对于多种方法:

_.bindAll(this);

最后,值得注意的是,在您的特定示例中您实际上不需要执行任何操作:只需执行即可

this.changeColor = function () {
div.css("background", "#FF0000");
};

而不是你所拥有的,即引用传入的 div 变量,而不是存储在 this.div 中的引用,因为它们是同一件事。

关于javascript - 使用 jQuery 在 JavaScript 对象中使用 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6687399/

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