Search code examples
javascripttypescriptprototype

can I add non static method to external class using prototypes?


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?


Solution

  • 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.