jQuery each() closure - how to access outside variable

99封情书 提交于 2019-12-20 12:14:24

问题


What's the best way to access my this.rules variable from within $.each()? Any explanation of why/how would also be helpful!

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)
}

回答1:


Store a reference to this -- name it self, for example --, before calling .each(), and then access rules using self.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)
}



回答2:


The answer above by João Silva is not a good solution as it creates a global variable. You are not actually passing a "self" variable to the each function by reference, but are instead referencing the global "self" object.

In the example above "this" is the window object and setting "var self = this" isn't really doing anything.

The Window object has two self-referential properties, window and self. You can use either global variable to refer directly to the Window object.

In short, both window and self are references to the Window object, which is the global object of client-side javascript.

Creating a closure function is a better solution.

Screenshot showing window and self comparison




回答3:


it is more elegant without 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)
}


来源:https://stackoverflow.com/questions/12309264/jquery-each-closure-how-to-access-outside-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!