javascript - 自定义方法中的 jQuery 'this' 关键字

标签 javascript jquery scope this

在很多情况下,我都看到了 jQuery 如何修改 this 关键字以提供您希望实际存在的对象的伟大之处。太棒了....

但是,如果您的自定义对象具有引用 this 关键字但通过 jQuery 调用的自定义方法,您该如何处理这种情况。

例如:

var myCustomObject = {

    myCustomValue: 1,

    myCustomMethod: function () {
        switch (this.myCustomValue) {
            case ....
        }
    }

};

如果使用 jQuery 回调调用,“this”现在是 jQuery“上下文”,并且显然为 myCustomValue 返回未定义。

我注意到我可以直接引用实例,例如

switch (myCustomObject.myCustomValue) {}

但这似乎冗长得令人烦恼,我想知道这是否会导致任何意外的副作用......

此类场景的最佳实践是什么?

最佳答案

如果不必公开:

var myCustomObject = new (function()
{
    var myCustomValue = 1;
    this.myCustomMethod = function () {
        switch (myCustomValue) {

        }
    }
})();

如果是:

var myCustomObject = new (function()
{
    this.myCustomValue = 1;
    var self = this;
    this.myCustomMethod = function () {
        switch (self.myCustomValue) {

        }
    }
})();

self 可以随意命名。

关于javascript - 自定义方法中的 jQuery 'this' 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4201339/

相关文章:

javascript - 同时从循环和函数中退出

c - 为什么全局变量与此函数中的局部变量不同?

javascript - 使用 setTimeout 的自定义对象调用方法丢失范围

javascript - 在 Web Worker 中调整和压缩图像。我可以使用 Canvas 吗?

JavaScript - 平滑移动/调整大小

javascript - 如何从 Wordpress Thickbox 中传递一个值?

javascript - 从第一个对象创建的另一个对象中访问对象原型(prototype)的变量

javascript - three.js - 如何动态更改对象的不透明度?

javascript - 如何使用jquery刷新页面的一部分

javascript - 为 $.post ajax 请求定义自定义句柄函数