In my JavaScript class, I have a method called resetRule()
:
resetRule() {
let sheetRules = Array.from(this.sheet.rules);
sheetRules.forEach(function(node, i) {
if(node.name != undefined) {
newRule.sheet.deleteRule(i);
}
});
}
When you create an instance of a class
, you need to assign it to a variable like this:
const newRule = new NewRule(*params*);
The methods and properties of the class
can refer to the object using this.
For example:
this.method();
this.property;
My question is: How can we reference the variable that instantiated the class within a function called by one of its methods?
In other words, when a function inside a class method changes the scope and alters the definition of this
, how can we access the original variable that created the instance of the class when outside the scope of the class methods?
While working on this question, I discovered a way to set the this
value for a .forEach
loop like so:
resetRule() {
let sheetRules = Array.from(this.sheet.rules);
sheetRules.forEach(function(node, i) {
if(node.name != undefined) {
this.sheet.deleteRule(i);
}
}, this);
}
However, I'm aware that this solution relies on the capabilities of the .forEach
method. I still seek a general approach to handle such situations.