gpt4 book ai didi

javascript - 从类中绑定(bind)函数时保存 "this"

转载 作者:行者123 更新时间:2023-11-30 00:07:07 24 4
gpt4 key购买 nike

我有一个简单的 JavaScript 类:

function MyCounter() {
this.counter = 0;
$('#button').click(this.run);
}

MyCounter.prototype.run = function() {
this.counter += 1;
return console.log(this.counter);
};

这个类是这样调用的:

var myCounter = new MyCounter();

HTML 包含一个带有 ID="button"的可点击按钮。单击此按钮应该会增加 myCounter 实例中的内部变量。显然,它失败是因为 this.counter 不存在,因为在执行绑定(bind)处理程序时 this 等于事件,而不是 myCounter 实例.

克服这个问题的粗略技巧是将“this”保存到其他变量并将调用实际处理程序包装到匿名函数中:

function MyCounter() {
this.counter = 0;
var this2 = this;
$('#button').click(function() {
this2.run();
});
}

有没有更好、更简洁的方法?或者至少,可能存在关于如何命名此类“临时 this”变量的通用协议(protocol)/风格指南?

最佳答案

你可以只使用.bind():

$('#button').click(this.run.bind(this));

.bind() 创建一个迷你 stub 函数,它基本上为您执行此操作:

var self = this;
$('#button').click(function() {
return self.run();
});

关于javascript - 从类中绑定(bind)函数时保存 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38105978/

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