Can I add using prototypes function for a class instance?
so I’ll be able to use this
or __proto__
keyword inside my method, for example:
JavaScript
x
21
21
1
class PersonClass {
2
name: string;
3
4
constructor(name: string) {
5
this.name = name;
6
}
7
8
sayHello() {
9
console.log(`hello, my name is ${this.name} and I'm a ${this.type}`);
10
}
11
}
12
13
PersonClass.prototype.type = "human";
14
PersonClass.prototype.PrintType = () => {
15
console.log(`I'm a ${PersonClass.prototype.type}`);
16
};
17
18
const aria = new PersonClass("Ned Stark");
19
aria.sayHello();
20
aria.PrintType();
21
this code works of course, but I wish to add something like
JavaScript
1
4
1
PersonClass.prototype.SayHello2 = () => {
2
console.log(this.name, caller.__proto__.name);
3
};
4
which of course fails.
is it even possible?
Advertisement
Answer
Your SayHello2
should be a non-arrow function to access the properties you are looking for:
JavaScript
1
4
1
PersonClass.prototype.SayHello2 = function () {
2
console.log(this.name, this.type);
3
};
4
which produces:
JavaScript
1
2
1
"Ned Stark", "human"
2
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.