为什么我的实例 属性 在 class 方法中使用时未定义?

Why is my instance property undefined when used in a class method?

当尝试 运行 cow1.voice(); 时,我在控制台中不断收到错误消息。

Uncaught ReferenceError: type is not defined

class Cow {
  constructor(name, type, color) {
    this.name = name;
    this.type = type;
    this.color = color;
  };
  voice() {
    console.log(`Moooo ${name} Moooo ${type} Moooooo ${color}`);
  };
};

const cow1 = new Cow('ben', 'chicken', 'red');

type等是你的class的实例变量,所以你需要用this来访问它们。提供给构造函数的初始变量 nametypecolor 用于 class 初始化,在构造函数之外不可用。

class Cow {
  constructor(name, type, color) {
    this.name = name;
    this.type = type;
    this.color = color;
  };

  voice() {
    // Access instance vars via this
    console.log(`Moooo ${this.name} Moooo ${this.type} Moooooo ${this.color}`);
  };
};