【问题标题】:jQuery each() closure - how to access outside variablejQuery each() 闭包 - 如何访问外部变量
【发布时间】:2012-08-31 19:34:14
【问题描述】:

从 $.each() 中访问 this.rules 变量的最佳方法是什么?任何有关原因/方式的解释也会有所帮助!

app.Style = function(node) {
    this.style = node;
    this.rules = [];
    var ruleHolder = node.find('Rule');

    $.each(ruleHolder, function(index, value) {
        var myRule = new app.Rule($(ruleHolder[index]));
        this.rules.push(myRule);
    });

    console.log(this.rules)
}

【问题讨论】:

    标签: jquery closures


    【解决方案1】:

    在调用.each()之前存储对this的引用——将其命名为self,然后使用self.rules访问rules

    app.Style = function(node) {
        this.style = node;
        this.rules = [];
        var ruleHolder = node.find('Rule');
    
        var self = this;
        $.each(ruleHolder, function(index, value) {
            var myRule = new app.Rule($(ruleHolder[index]));
            self.rules.push(myRule);
        });
    
        console.log(this.rules)
    }
    

    【讨论】:

    • 这会起作用,但我建议更明确地说明变量名称,因为 javascript 中的作用域可能有点令人困惑。你可以这样做: var Style_this = this;
    【解决方案2】:

    João Silva 的上述答案不是一个好的解决方案,因为它创建了一个全局变量。您实际上并没有通过引用将“self”变量传递给每个函数,而是引用了全局“self”对象。

    在上面的示例中,“this”是窗口对象,设置“var self = this”实际上并没有做任何事情。

    Window 对象有两个自引用属性,window 和 self。您可以使用任一全局变量直接引用 Window 对象。

    简而言之,window和self都是对Window对象的引用,Window对象是客户端javascript的全局对象。

    Creating a closure function is a better solution.

    Screenshot showing window and self comparison

    【讨论】:

    • 我不认为你是对的。在函数内部使用var 声明的变量绝不是全局变量。
    • 不,他是对的,在上面的上下文中,这指的是 Window,所以它根本就是一个全局变量。
    【解决方案3】:

    没有var self = this;会更优雅

    app.Style = function(node) {
        this.style = node;
        this.rules = [];
        var ruleHolder = node.find('Rule');
    
        $.each(ruleHolder, function(index, value) {
            var myRule = new app.Rule($(ruleHolder[index]));
            this.rules.push(myRule);
        }.bind(this));
    
        console.log(this.rules)
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-18
      • 1970-01-01
      • 1970-01-01
      • 2011-05-20
      • 1970-01-01
      • 2011-04-11
      • 2018-12-24
      • 1970-01-01
      • 2017-10-05
      相关资源
      最近更新 更多