JavaScript/NodeJS : Invoking object methods inside the same object: why is "this." mandatory?

标签 javascript node.js function oop scope

我是 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() 是在类外部全局声明的。

enter image description here

关于JavaScript/NodeJS : Invoking object methods inside the same object: why is "this." mandatory?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52261393/

相关文章:

javascript - 在 sequelize 上, "include"的 "findOne"不工作

javascript - 如何从系统获取图像以加载到html5的canvas中

node.js - Mocha 单元测试: where to create variables

mysql - 带有 MySQL 的 OpenShift 上的 SailsJS

r - 查找所有包含单词 `list` 的 Base R 函数名称

function - Go中的函数和方法有什么区别?

javascript - 使用 JavaScript 将类添加到特定的 href 元素

javascript - Firebase 存储不返回 downloadURL

node.js - 省略列名/将对象直接插入 node-postgres

javascript - 为什么这个函数没有被调用?