为什么我不能通过其原型访问类中"this"的属性?

Nic*_*net 0 javascript prototype ecmascript-6 es6-class

我写了这个类并为它设置了一个数组属性.然后,我想在此数组中添加一个项目.

然而,当我尝试这样做,我得到的错误"未捕获TypeError:无法读取属性pushundefined".

这不可能吗?

class test {
  constructor() {
    this.myArray = [];
  }

  myMethod() {
    this.myArray.push("ok");
  }
};

console.log(test.prototype.myMethod());
Run Code Online (Sandbox Code Playgroud)

Seb*_*mon 5

这不是如何使用类.您需要test先使用实例化new test().在constructor你的情况是从来没有所谓的,所以this.myArray从来没有定义.

这是唯一可行的方法:

let testInstance = new test();

testInstance.myMethod();
Run Code Online (Sandbox Code Playgroud)

这样,constructor调用它就不会有错误.

当然,接下来你需要一些方法来检索你的数组,以便看到效果.