0

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:

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?

MarioG8
  • 5,122
  • 4
  • 13
  • 29
Or Yaacov
  • 3,597
  • 5
  • 25
  • 49
  • How exactly does it fail? Aren't classes compiled into "other primitives" (functions/objects) ? So if you can find that "other primitive" in the compiled code, surely you will be able to slap something onto the prototype. It's not "protected" afaik. Seems you can't with ES6: https://stackoverflow.com/questions/37680766/how-to-change-classs-prototype-in-es6 . How about extending the class like a normal person :p ? – Ярослав Рахматуллин Oct 31 '21 at 17:43
  • Does this answer your question? [How to change Class's Prototype in ES6](https://stackoverflow.com/questions/37680766/how-to-change-classs-prototype-in-es6) – Ярослав Рахматуллин Oct 31 '21 at 17:46
  • Can you clarify what you mean by "external class"? – Ray Toal Oct 31 '21 at 17:51
  • @ЯрославРахматуллин no this is not solving my issue. actually someone just did answer the right answer, which is disappeared now – Or Yaacov Oct 31 '21 at 17:56
  • @RayToal third party class, or for example Array class (as I mentioned before someone already wrote the right answer, and hopefully s/he will post it again soon) – Or Yaacov Oct 31 '21 at 18:04
  • 1
    Sorry, that was me. I answered it right away but then I deleted it when I saw the words "external class" and wanted to ask you for clarification. I have undeleted it, hope it helps. – Ray Toal Oct 31 '21 at 18:17
  • @RayToal it did, thank you! – Or Yaacov Oct 31 '21 at 18:18

2 Answers2

1

Your SayHello2 should be a non-arrow function to access the properties you are looking for:

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.

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
1

This should works:

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

    aria.SayHello2(); // "Ned Stark"
Or Yaacov
  • 3,597
  • 5
  • 25
  • 49
Shalom Peles
  • 2,285
  • 8
  • 21