22

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

3 Answers 3

26

Store a reference to this -- name it self, for example --, before calling .each(), and then access rules using 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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

This will work but I would recommend being more explicit about the variable name since scoping in javascript can be a bit confusing. You could do it like this: var Style_this = this;
1

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

Comments

0

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.

In the example above "this" is the window object and setting "var self = this" isn't really doing anything.

The Window object has two self-referential properties, window and self. You can use either global variable to refer directly to the Window object.

In short, both window and self are references to the Window object, which is the global object of client-side javascript.

Creating a closure function is a better solution.

Screenshot showing window and self comparison

2 Comments

I don't think you're right about this. Variables declared with var inside of a function are never global variables.
No, he is right, in the above context this is reffering to Window and so it is a global variable at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.