首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >jQuery each()闭包-如何访问外部变量

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

Stack Overflow用户
提问于 2012-09-07 06:21:12
回答 3查看 26.3K关注 0票数 21

从$.each()中访问this.rules变量的最佳方式是什么?任何解释为什么/如何也是有帮助的!

代码语言:javascript
复制
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)
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-09-07 06:22:13

在调用.each()之前存储对this的引用--例如,将其命名为self --然后使用self.rules访问rules

代码语言:javascript
复制
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)
}
票数 23
EN

Stack Overflow用户

发布于 2017-06-21 05:28:03

João Silva上面的答案不是一个好的解决方案,因为它创建了一个全局变量。实际上,您并没有通过引用将"self“变量传递给each函数,而是引用了全局"self”对象。

在上面的示例中,"this“是窗口对象,而设置"var self = this”实际上并不起什么作用。

Window对象有两个自引用属性: window和self。您可以使用这两个全局变量中的任何一个直接引用窗口对象。

简而言之,window和self都是对Window对象的引用,Window对象是客户端javascript的全局对象。

Creating a closure function is a better solution

Screenshot showing window and self comparison

票数 0
EN

Stack Overflow用户

发布于 2018-03-14 18:16:33

没有var self = this;会更优雅

代码语言:javascript
复制
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)
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12309264

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档