我可以使用原型将非静态方法添加到外部 class 吗?
can I add non static method to external class using prototypes?
我可以为 class 实例添加使用原型函数吗?
所以我可以在我的方法中使用 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);
};
这当然失败了。
有可能吗?
你的 SayHello2
应该是一个非箭头函数来访问你正在寻找的属性:
PersonClass.prototype.SayHello2 = function () {
console.log(this.name, this.type);
};
产生:
"Ned Stark", "human"
别忘了您还可以访问实例的 constructor
属性,从而允许您访问与您的 类.
关联的所有内容
这应该有效:
PersonClass.prototype.SayHello2 = function() {
console.log(this.name);
};
aria.SayHello2(); // "Ned Stark"
我可以为 class 实例添加使用原型函数吗?
所以我可以在我的方法中使用 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);
};
这当然失败了。
有可能吗?
你的 SayHello2
应该是一个非箭头函数来访问你正在寻找的属性:
PersonClass.prototype.SayHello2 = function () {
console.log(this.name, this.type);
};
产生:
"Ned Stark", "human"
别忘了您还可以访问实例的 constructor
属性,从而允许您访问与您的 类.
这应该有效:
PersonClass.prototype.SayHello2 = function() {
console.log(this.name);
};
aria.SayHello2(); // "Ned Stark"