jQuery each() closure - how to access outside variable

前端 未结 3 1147
时光取名叫无心
时光取名叫无心 2021-02-05 07:44

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) {
    th         


        
3条回答
  •  我在风中等你
    2021-02-05 08:03

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

提交回复
热议问题