jQuery each() 闭包 - 如何访问外部变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12309264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery each() closure - how to access outside variable
提问by chris_mac
What's the best way to access my this.rules variable from within $.each()? Any explanation of why/how would also be helpful!
从 $.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)
}
回答by Jo?o Silva
Store a reference to this
-- name it self
, for example --, before calling .each()
, and then access rules
using self.rules
:
在调用之前存储对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)
}
回答by Dustin Page
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.
Jo?o Silva 上面的答案不是一个好的解决方案,因为它创建了一个全局变量。您实际上并不是通过引用将“self”变量传递给每个函数,而是引用全局“self”对象。
In the example above "this" is the window object and setting "var self = this" isn't really doing anything.
在上面的例子中,“this”是窗口对象,设置“var self = this”并没有真正做任何事情。
The Window object has two self-referential properties, window and self. You can use either global variable to refer directly to the Window object.
Window 对象有两个自引用属性,window 和 self。您可以使用任一全局变量直接引用 Window 对象。
In short, both window and self are references to the Window object, which is the global object of client-side javascript.
总之,window和self都是对Window对象的引用,Window对象是客户端javascript的全局对象。
Creating a closure function is a better solution.
回答by Zoltán Süle
it is more elegant without var self = this;
没有它更优雅 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)
}