gpt4 book ai didi

javascript - 在回调函数中调用类方法

转载 作者:行者123 更新时间:2023-11-28 17:54:01 25 4
gpt4 key购买 nike

我有以下类(class)。它有一个错误,因为 this.handlers(第 2 行)中的引用与 this.setTimeRange(第 4 行)中的引用不同

function Synchronized() {
this.handlers = [];
$("#masterSlider").rangeSlider();

$("#masterSlider").bind("valuesChanging", function(e, data) {
this.setTimeRange(data.values.min, data.values.max);
});

}

Synchronized.prototype = {
setTimeRange: function(lowerBound, upperBound) {
console.log(lowerBound, upperBound);
this.lowerBound = lowerBound;
this.upperBound = upperBound;
$("#masterSlider").rangeSlider("bounds", this.lowerBound, this.upperBound);
},
}

如何从回调函数中调用类方法?

最佳答案

您有多种选择。最常见的三种:

创建一个变量来存储可以关闭的this副本

var that = this;
$("#masterSlider").bind("valuesChanging", function(e, data) {
that.setTimeRange(data.values.min, data.values.max);
});

在匿名函数上使用function.prototype.bind来返回另一个具有指定值this的函数:

$("#masterSlider").bind("valuesChanging", (function(e, data) {
this.setTimeRange(data.values.min, data.values.max);
}).bind(this));

使用 ES6 箭头函数而不是匿名函数:

$("#masterSlider").bind("valuesChanging", (e, data) => this.setTimeRange(data.values.min, data.values.max));

关于javascript - 在回调函数中调用类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44867635/

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