I have this method of a JavaScript class that I've created:
resetRule() {
let sheetRules = Array.from(this.sheet.rules);
sheetRules.forEach(function(node, i) {
if(node.name != undefined) {
newRule.sheet.deleteRule(i);
}
});
}
when you instantiate a class
, it essentially has to be set to a variable, like so:
const newRule = new NewRule(*params*);
and the methods/properties of said class
can refer to the class object using this.
like so:
this.method();
this.property;
What I'd like to know is: how does one refer back to the variable that instantiated the class within a function that is called by a method of said class?
To be even clearer: a function that is called within a method of a class alters the scope, which also means it alters the definition of this.
. My question is: how do you get around this? How could you access the variable that instantiated the class
when you are out the of scope of the methods within said class
?
As I was composing this question, I realized that you can set the this
value for a .forEach
loop like this:
resetRule() {
let sheetRules = Array.from(this.sheet.rules);
sheetRules.forEach(function(node, i) {
if(node.name != undefined) {
this.sheet.deleteRule(i);
}
}, this);
}
However, the way this code works is something that--as far as I know--is just a benefit of the .forEach
method, and I'd still like to know how it should be handled in general.