(版主注意:我已经阅读并理解了这个优秀的帖子:How does the "this" keyword work?,它与这个问题无关)
我没有发现混合 jQuery 和 OOP 的类似情况将上下文传递给 jQuery 回调。
我定义了一个名为MySlider的类和一个名为registerListeners的方法, 但我无法从 jQuery 回调中获取对 MySlider 对象的引用。
有什么想法吗?
MySlider.prototype.registerListeners = function () {
var hello = this;
$('#sl').slider({
slide: function (event, ui) {
console.log(event + " " + ui);
// how to access 'hello' from here ?
}
}) ;
};
提前致谢。
最佳答案
只需访问它即可!您已经创建了一个闭包,其中可以从内部函数访问外部函数中定义的变量。
变量的某种副本与函数对象一起存储。如果您在定义函数后执行了 var hello = "tricked you!"
,则在内部函数中找到的 hello
值将更新以匹配。
关于javascript - 将对象引用传递给 jQuery 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51163215/