我是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()
...
}
}
这是因为与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!');
}