1

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();

2
  • 2
    You probably shouldn't replace the entire prototype: User.prototype.who_auto = function () ...! Commented Mar 3, 2021 at 12:01
  • Hmmm "probably"... I like your thinking... there are no definites in life... haha Thanks! Commented Mar 3, 2021 at 12:18

1 Answer 1

1

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();

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

2 Comments

``` const User = function(name) { this.name = name; this.chatroom = null; } User.prototype = { send: function(message, to) { this.chatroom.send(message, this, to); }, recieve: function(message, from) { console.log(${from.name} to ${this.name}: ${message}); } } const Chatroom = function() { let users = {}; // list of users return { register: function(user) { users[user.name] = user; user.chatroom = this; } } } ``` Mark, I've been working along with this tutorial and it is striking me as strange why the above works
Probably should have added that to the original post.. thanks Mark

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.