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)
}
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.
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.
var FunctionToCall; (function () { //...... FunctionToCall = function() { //...... }; //........ } (); And then you can call FunctionToCall.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With