从$.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)
}
发布于 2012-09-07 06:22:13
在调用.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)
}
发布于 2017-06-21 05:28:03
João Silva上面的答案不是一个好的解决方案,因为它创建了一个全局变量。实际上,您并没有通过引用将"self“变量传递给each函数,而是引用了全局"self”对象。
在上面的示例中,"this“是窗口对象,而设置"var self = this”实际上并不起什么作用。
Window对象有两个自引用属性: window和self。您可以使用这两个全局变量中的任何一个直接引用窗口对象。
简而言之,window和self都是对Window对象的引用,Window对象是客户端javascript的全局对象。
发布于 2018-03-14 18:16:33
没有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
复制相似问题