I am attempting to define a class called "User"... then further along in the code I am trying to add a method to the class by writing to "prototype". I'm not sure if my terminology is correct here... though I would like to have the method "who_auto" available to all future instances of "User"...
Trying out this code in JSFiddle... is giving me the error message: "Uncaught TypeError: pp.who_auto is not a function"
Here's my code:
class User {
constructor(name) {
this.name = name;
this.chatroom = null;
}
who() {
return `I am ${this.name}`;
}
}
User.prototype = {
who_auto: function() {
console.log(`
Hello, I am ${this.name}
`);
}
}
const pp = new User('peter parker');
console.log(pp);
console.log(pp.who());
pp.who_auto();
You overwritten the prototype instead of adding a property to the prototype. Below codes works.
class User {
constructor(name) {
this.name = name;
this.chatroom = null;
}
who() {
return `I am ${this.name}`;
}
}
User.prototype.who_auto = function() {
console.log(`Hello, I am ${this.name}`);
}
const pp = new User('peter parker');
console.log(pp);
console.log(pp.who());
pp.who_auto();