Ben Johnson
Ben Johnson

Reputation: 358

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

Upvotes: 3

Views: 407

Answers (1)

Clarity
Clarity

Reputation: 10873

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

Upvotes: 7

Related Questions