[英]can I add non static method to external class using prototypes?
Can I add using prototypes function for a class instance?我可以为类实例添加 using 原型函数吗?
so I'll be able to use this
or __proto__
keyword inside my method, for example:所以我将能够在我的方法中使用
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();
this code works of course, but I wish to add something like这段代码当然有效,但我想添加类似的东西
PersonClass.prototype.SayHello2 = () => {
console.log(this.name, caller.__proto__.name);
};
which of course fails.这当然失败了。
is it even possible?甚至有可能吗?
Your SayHello2
should be a non-arrow function to access the properties you are looking for:你的
SayHello2
应该是一个非箭头函数来访问你正在寻找的属性:
PersonClass.prototype.SayHello2 = function () {
console.log(this.name, this.type);
};
which produces:它产生:
"Ned Stark", "human"
Don't forget you also have access to the constructor
property of an instance as well, allowing you to access everything associate with your classes.不要忘记您还可以访问实例的
constructor
属性,允许您访问与您的类相关的所有内容。
This should works:这应该有效:
PersonClass.prototype.SayHello2 = function() {
console.log(this.name);
};
aria.SayHello2(); // "Ned Stark"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.