Javascript / NodeJS:在同一个对象中调用对象方法:为什么“this。”是强制性的?

问题描述 投票:0回答:2

我是Node / Javascript(ES6)的新手。见下面的例子:

class MyClass {

    myTest() {
          console.log('it works')
        }

    runMyTest() {
          this.myTest()
        }

}

如果我省略this.行中的this.myTest(),我会收到运行时错误:

      myTest()
      ^

ReferenceError:未定义myTest

在我看来,必须调用在调用者的同一对象(在本例中为Class Object)中声明的方法,需要this.method()

那是对的吗?

以类似的方式,我看到父方法(子类对象)需要super.parent Method()。

来自Ruby /其他OO语言对我来说听起来很奇怪。

为什么在JS中强制使用this. / super.的原因?


更新:

我找到的小解决方法(避免这种方法重复):

class MyClass {

    myTest() {
          console.log('it works')
        }

    runMyTestManyTimes() {
          const mytest = this.mytest

          myTest()
          ...
          myTest()
          ...
          myTest()
          ...

        }

}
javascript node.js function oop scope
2个回答
3
投票

因为this引用了MyClass的实例(使用原型上的类方法)并且没有它,所以你的方法看不到函数,因为它没有找到正确的位置。它将使用其范围内的任何内容,即如果函数myTest()在全局范围之外声明。

enter image description here


1
投票

这是因为与Java或C#不同(这很可能是你从中看到过这种做法的地方),JavaScript可以拥有不属于该类的函数。

在这种情况下你会做什么?

class MyClass {
  myTest() {
    console.log('it works');
  }

  runMyTest() {
    myTest(); // oops
  }
}

function myTest() {
  console.error('It does not work! Oh my god everything is on fire!');
}
© www.soinside.com 2019 - 2024. All rights reserved.