简体   繁体   中英

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

When trying to run cow1.voice(); and I keep getting an error in the console.

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 and others are instance variables of your class, so you need to use this to access them. The initial variables name , type , color , provided to the constructor are used for class initialisation and aren't available outside of constructor.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM