Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery each() closure - how to access outside variable

Tags:

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)
}
like image 515
chris_mac Avatar asked Sep 06 '12 22:09

chris_mac


People also ask

How do you access the function variable outside?

To access a variable outside a function in JavaScript make your variable accessible from outside the function. First, declare it outside the function, then use it inside the function. You can't access variables declared inside a function from outside a function.

Can we access variable outside function in JavaScript?

Variables declared Globally (outside any function) have Global Scope. Global variables can be accessed from anywhere in a JavaScript program. Variables declared with var , let and const are quite similar when declared outside a block.

How do you call a variable function in jquery?

var FunctionToCall; (function () { //...... FunctionToCall = function() { //...... }; //........ } (); And then you can call FunctionToCall.


1 Answers

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)
}
like image 63
João Silva Avatar answered Oct 12 '22 00:10

João Silva