【问题标题】:Access property in class from prototype override从原型覆盖访问类中的属性
【发布时间】:2020-02-07 14:44:16
【问题描述】:

不确定我的问题措辞是否正确。但基本上我有一个类,但我想为它写一个新方法。假设我的班级是这样的:

class MyClass {
  constructor () {
    this.someProperty = []

    this.someMethod = this.someMethod.bind(this)
  }

  function someMethod () {
    // do something
  }
}

现在,因为我无法直接访问这个类,所以我将使用prototype 创建一个新方法

MyClass.prototype.myNewMethod = function (params) {
  // do something else
  // how to access someProperty? And to the bind to MyClass?
}

但是现在说我想访问someProperty 并且还想在这个新方法上执行bind。我该怎么做?

事实上,我的方法创建一开始就正确吗?无论如何,我想要的是它对类内的this 具有相同的访问权限。我该怎么做?

【问题讨论】:

  • 您只需致电myClassInstance.myNewMethod(args) 即可。但是不行,你不能在不修改构造函数的情况下自动绑定这个方法。

标签: javascript class prototype prototype-programming


【解决方案1】:

我不明白你想要做什么,但你可以访问它:

class MyClass {
  constructor () {
    this.someProperty = [];

  }

  someMethod = function() {
    console.log(this.someProperty);
  }
}

var cc = new MyClass();
cc.someMethod();

【讨论】: