1

我正在尝试定义一个名为“User”的类......然后在代码中我试图通过写入“prototype”来向该类添加一个方法。我不确定我的术语在这里是否正确......虽然我希望所有未来的“用户”实例都可以使用“who_auto”方法......

在 JSFiddle 中试用此代码...给了我错误消息:“未捕获的 TypeError: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();

4

1 回答 1

1

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

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

于 2021-03-03T12:06:40.000 回答