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?

7
  • 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: stackoverflow.com/questions/37680766/… . How about extending the class like a normal person :p ? Commented Oct 31, 2021 at 17:43
  • Does this answer your question? How to change Class's Prototype in ES6 Commented Oct 31, 2021 at 17:46
  • Can you clarify what you mean by "external class"? Commented Oct 31, 2021 at 17:51
  • @ЯрославРахматуллин no this is not solving my issue. actually someone just did answer the right answer, which is disappeared now Commented Oct 31, 2021 at 17:56
  • 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. Commented Oct 31, 2021 at 18:17

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

This should works:

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

    aria.SayHello2(); // "Ned Stark"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.