【问题标题】:Javascript Object - using jQuery and thisJavascript 对象 - 使用 jQuery 和 this
【发布时间】:2023-03-12 14:09:02
【问题描述】:

当在对象函数中使用 jQuery 方法时(即 - .each()),“this”变量将引用被迭代的对象。没有“this”如何访问对象的功能?我意识到这有点令人困惑,所以:

test.prototype.init = function(node) {
    node.children().each(function() {
        //call test.anotherFunction() here
        //Would normally call this.anotherFunction(), 
        //  but "this" refers to the current child.
    });
}
test.prototype.anotherFunction = function() {
    //whatever
}

帮助?

【问题讨论】:

    标签: javascript jquery object this javascript-objects


    【解决方案1】:

    this 的副本保存到局部变量中(在本例中命名为self,但您可以随意命名)并在嵌入函数中使用保存的副本:

    test.prototype.init = function(node) {
        var self = this;
        node.children().each(function() {
            // use self here to reference the host object
        });
    }
    test.prototype.anotherFunction = function() {
        //whatever
    }
    

    【讨论】:

    • +1 var self = this; 常用于保持父级的作用域。
    • 我更喜欢var that = this;,因为self 会影响全局window.self
    • 呼应@jbabey 对self 的关注。
    • facepalm 我不敢相信我没有想到这一点。使用'obj'会有什么顾虑吗?让我的大脑比“那个”更快乐。
    • window.self 指的是window 上下文。所以用当前的上下文来遮蔽它是有意义的。
    【解决方案2】:

    您还可以使用.bind 函数来更改函数的上下文。无论您提供给.bind 的任何参数都将在函数执行时成为该函数的所有者,从而成为this 的值。

    test.prototype.init = function(node) {
        node.children().each(function(i,el) {
            // this = test.prototype
            // i = index of the current child of `node`
            // el = HTML node of current child
            // $(el) = jQuery object representing current child
        }.bind(this));
    };
    

    【讨论】:

    • 使用绑定是一个不错的方法
    【解决方案3】:

    您可以在迭代之前定义要引用的对象。您将能够接近它,因为它仍在范围内。

    var currentObject = this;
    
    test.prototype.init = function(node) {
        node.children().each(function() {
            currentObject.anotherFunction();
        });
    }
    test.prototype.anotherFunction = function() {
        //whatever
    }
    

    【讨论】:

    • 对象上的方法的全部意义在于您可以引用调用该方法的对象。在进行方法调用之前设置全局变量而不是在方法中使用实际的对象引用不是一种好的风格,而且容易出现各种潜在问题。
    猜你喜欢
    • 2015-01-22
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 2013-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多