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

时间:2019-09-09 17:16:33

标签: javascript instance-variables es6-class

尝试运行cow1.voice();时,控制台中始终出现错误。

  

未捕获的ReferenceError:类型未定义

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

1 个答案:

答案 0 :(得分:6)

type和其他变量是您的类的实例变量,因此您需要使用this来访问它们。提供给构造函数的初始变量nametypecolor用于类初始化,在构造函数之外不可用。

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}`);
  };
};