【发布时间】: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