【问题标题】:can I add non static method to external class using prototypes?我可以使用原型向外部类添加非静态方法吗?
【发布时间】:2021-10-31 17:34:54
【问题描述】:

我可以为类实例添加使用原型函数吗?

所以我可以在我的方法中使用this__proto__ 关键字,例如:

class PersonClass {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  sayHello() {
    console.log(`hello, my name is ${this.name} and I'm a ${this.type}`);
  }
}

PersonClass.prototype.type = "human";
PersonClass.prototype.PrintType = () => {
  console.log(`I'm a ${PersonClass.prototype.type}`);
};

const aria = new PersonClass("Ned Stark");
aria.sayHello();
aria.PrintType();

这段代码当然可以,但我想添加类似的东西

PersonClass.prototype.SayHello2 = () => {
  console.log(this.name, caller.__proto__.name);
};

当然失败了。

有可能吗?

【问题讨论】:

  • 它到底是怎么失败的?类不是编译成“其他原语”(函数/对象)吗?因此,如果您可以在编译后的代码中找到“其他原语”,那么您肯定可以在原型上添加一些东西。它不是“受保护的”afaik。似乎您不能使用 ES6:stackoverflow.com/questions/37680766/…。像普通人一样扩展课程怎么样:p?
  • 这能回答你的问题吗? How to change Class's Prototype in ES6
  • 你能解释一下“外部类”是什么意思吗?
  • @ЯрославРахматуллин 不,这不能解决我的问题。实际上有人刚刚回答了正确的答案,现在消失了
  • 对不起,那是我。我马上就回答了,但是看到“外班”这几个字就删了,想请你澄清一下。我已取消删除,希望对您有所帮助。

标签: javascript typescript prototype


【解决方案1】:

你的SayHello2 应该是一个非箭头函数来访问你正在寻找的属性:

PersonClass.prototype.SayHello2 = function () {
  console.log(this.name, this.type);
};

产生:

"Ned Stark",  "human" 

不要忘记,您还可以访问实例的 constructor 属性,允许您访问与您的类相关的所有内容。

【讨论】:

    【解决方案2】:

    这应该可行:

        PersonClass.prototype.SayHello2 = function() {
          console.log(this.name);
        };
    
        aria.SayHello2(); // "Ned Stark"
    

    【讨论】:

      猜你喜欢
      • 2017-01-03
      • 2016-09-19
      • 2021-12-25
      • 1970-01-01
      • 2014-05-14
      • 1970-01-01
      • 2017-09-01
      • 1970-01-01
      • 2023-03-25
      相关资源
      最近更新 更多