在javascript中引用类实例化器

在javascript中引用类实例化器,javascript,scope,this,Javascript,Scope,This,我创建了一个JavaScript类的以下方法: resetRule() { let sheetRules = Array.from(this.sheet.rules); sheetRules.forEach(function(node, i) { if(node.name != undefined) { newRule.sheet.deleteRule(i); } }); } 实例化类时,必须将其设置为变量,如下所示: const newRule = n

我创建了一个JavaScript类的以下方法:

resetRule() {
  let sheetRules = Array.from(this.sheet.rules);
  sheetRules.forEach(function(node, i) {
    if(node.name != undefined) {
      newRule.sheet.deleteRule(i);
    }
  });
}
实例化
类时,必须将其设置为变量,如下所示:

const newRule = new NewRule(*params*);
所述
类的方法/属性可以使用
这样引用类对象。
如下:

this.method();
this.property;
我想知道的是:如何在一个由所述类的方法调用的函数中引用实例化该类的变量

更清楚的是:在类的方法中调用的函数会改变作用域,这也意味着它会改变
this.
的定义。我的问题是:你是如何解决这个问题的当您不在所述
中的方法范围内时,如何访问实例化
类的变量?


当我编写这个问题时,我意识到可以为
.forEach
循环设置
this
值,如下所示:

resetRule() {
  let sheetRules = Array.from(this.sheet.rules);
  sheetRules.forEach(function(node, i) {
    if(node.name != undefined) {
      this.sheet.deleteRule(i);
    }
  }, this);
}

然而,据我所知,这段代码的工作方式只是
.forEach
方法的一个优点,我仍然想知道一般应该如何处理它。

希望这会对您有所帮助,使用您的示例

类规则{
建造师(规则){
此页={
规则:规则
}
}
日志(){
console.log('rules:',this.sheet.rules)
}
重置规则(){
设sheetRules=Array.from(this.sheet.rules);

让self=this;//如果我没有误解的话,您正在寻找保留您的范围的方法?您在这里有一些选择

直接的答案是在调用这些方法时使用或指定
this
的上下文

或者,您可以只在需要时提供
的范围:

var MyClass = function () {
    // Here we bind the local scope to a variable that will give us context where necessary.
    // While it's not needed here, it can give context and set a pattern of reability through repitition.
    var vm = this;

    vm.methodA = function () {
        // We continue to set our 'vm' pointer variable when needed.
        var vm = this;

        globalMethod.then(function () {
            // We're able to retain context of our `this` through having scope of our 'vm' variable.
            vm.methodB();
        });
    };

    vm.methodB = function () {
        console.log('I did stuff!');
    };
};

您可以创建一个名为
self
的临时变量,或者允许您使用包含“this”实例的对象以及传递给forEach的匿名函数中的某个对象,
this
,当您没有指定另一个变量用作
this
时,该变量将引用
sheetRules

resetRule() {
  let sheetRules = Array.from(this.sheet.rules);
  let self = this;
  sheetRules.forEach(function(node, i) {
    if(node.name != undefined) {
    self.sheet.deleteRule(i);
    }
  });
}

所述类的方法/属性可以引用使用此
的类对象。”-
引用该类的本地实例class@vol7ron如果
this.method()
包含一个函数,您想尝试使用
this
来引用该函数中的“实例”,但它不起作用。因此,问题是……我可能需要您证明您可以只做
让foo=this
,也许这就是您想要的need@Lux那会在构造函数中吗?比如:
classnewclass{constructor(a,b){this.a=a;this.b=b;让foo=this}}
?或者它只是随意地放在方法或其他东西之间?是的,这似乎是普遍的共识。谢谢你,先生。对于那些标记为重复的人,我认为这会发生,但正如我所说,我不知道如何问这个问题,所以…谢谢你间接回答我的问题!!