从$.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) }
解决方法
存储对此的引用 – 例如 – 将其命名为self,然后再调用.each(),然后使用self.rules访问规则:
app.Style = function(node) { this.style = node; this.rules = []; var ruleHolder = node.find('Rule'); var self = this; $.each(ruleHolder,value) { var myRule = new app.Rule($(ruleHolder[index])); self.rules.push(myRule); }); console.log(this.rules) }