【问题标题】:Why is my instance property undefined when used in a class method?为什么在类方法中使用我的实例属性未定义?
【发布时间】:2020-01-11 11:38:01
【问题描述】:

尝试运行 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 而不是name 上失败的原因是因为name 指的是window.name。 (这并不能回答问题,但可能仍然有用。)

标签: javascript instance-variables es6-class


【解决方案1】:

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

【讨论】:

  • 是的,但是当我在控制台中运行 cow1.voice() 时出现错误而不是模板化字符串?
  • 那是因为没有定义变量,需要使用this.type
  • 你能把更新的sn-p代码发给我吗?让我看看我是不是出错了?
  • 我认为说实例变量“在构造函数之外不可用”是不正确的。它们可用,但仅限于 this
  • @RobertStiffler 真的很好,我已经混合了用于初始化的变量和实例变量。我已经更新了答案。
猜你喜欢
  • 2016-09-26
  • 2015-07-16
  • 1970-01-01
  • 2018-09-05
  • 2019-08-30
  • 1970-01-01
  • 2021-07-17
  • 2017-08-28
  • 1970-01-01
相关资源
最近更新 更多