我是 Node/Javascript (ES6) 的新手。 请参阅下面的示例:
class MyClass {
myTest() {
console.log('it works')
}
runMyTest() {
this.myTest()
}
}
如果我在 this.myTest()
行中省略 this.
,则会出现运行时错误:
myTest() ^
ReferenceError: myTest is not defined
在我看来,必须调用调用者的同一对象(在本例中为类对象)中声明的方法,需要 this.method()
正确吗?
以类似的方式,我发现(子类对象的)父方法需要 super.parentMethod()。
来自 Ruby/其他对我来说听起来很奇怪的面向对象语言。
为什么在JS中强制使用this.
/super.
?
更新:
我发现的小解决方法(以避免 this.method 重复):
class MyClass {
myTest() {
console.log('it works')
}
runMyTestManyTimes() {
const mytest = this.mytest
myTest()
...
myTest()
...
myTest()
...
}
}
最佳答案
因为 this
引用了 MyClass
的实例(带有原型(prototype)上的类方法),如果没有它,您的方法就不会看到该函数,因为它没有在正确的位置查找。它将使用其范围内的任何内容,即如果函数 myTest()
是在类外部全局声明的。
关于JavaScript/NodeJS : Invoking object methods inside the same object: why is "this." mandatory?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52261393/