jQuery each()闭包 - 如何访问外部变量

chr*_*mac 20 jquery closures

从$ .each()中访问my.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)
}
Run Code Online (Sandbox Code Playgroud)

Joã*_*lva 22

在调用之前存储引用this- self例如- 命名- ,.each()然后rules使用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)
}
Run Code Online (Sandbox Code Playgroud)