使用 .prototype 向 class 添加方法

Adding a method to a class using .prototype

我正在尝试定义一个名为“User”的 class...然后在代码中进一步尝试通过写入“原型”来向 class 添加一个方法。 我不确定我的术语在这里是否正确...尽管我希望“who_auto”方法可用于“User”的所有未来实例...

在 JSFiddle 中尝试这段代码...给我错误信息: “未捕获的类型错误:pp.who_auto 不是函数”

这是我的代码:

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

您覆盖了原型,而不是向原型添加 属性。以下代码有效。

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