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

Ben*_*son 2 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');
Run Code Online (Sandbox Code Playgroud)

Cla*_*ity 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}`);
  };
};

Run Code Online (Sandbox Code Playgroud)

  • 那是因为没有定义变量,所以需要使用`this.type`。 (3认同)
  • @RobertStiffler真的很不错,我在这里混合了用于初始化的变量和实例变量。我已经更新了答案。 (2认同)