javascript - 将对象引用传递给 jQuery 回调

标签 javascript jquery

(版主注意:我已经阅读并理解了这个优秀的帖子: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/

相关文章:

javascript - 重新触发动画

原型(prototype)上的 Javascript 私有(private)成员

javascript - with 中的哪些变量对象语句绑定(bind)?

javascript - 通过 jQuery 检查不透明度

javascript - 计算数字乘数后缀的更简单方法

javascript - 使用 Jquery 返回许多要在 html 中更新的值

jquery - 使用ajax和rest web服务上传文件

javascript - 使用jquery更新字段不会更新可观察的

php - 有类似的用于绘制图表(如 Google Charts)的库/类吗?

javascript - 我想要一个不使用 'click anywhere except this div' 或 'event.stopPropagation();' 的 '.length' 函数