Change prototype to new object: undefined

Hi,

Can anyone explain why my print to the console returns undefined with the following code:

function Dog(name) {
  this.name = name;
}

let terrier = new Dog("John");

Dog.prototype = {
  constructor: Dog,
  numLegs: 4
};

console.log(terrier.numLegs);

I would expect it to work like this does:

function Dog(name) {
  this.name = name;
}

let terrier = new Dog("John");

Dog.prototype.numLegs = 4;

console.log(terrier.numLegs);

My understanding was setting prototype to a new object was a quick way than setting each property individually, unless I’ve missed something?

Many thanks,

Fraser

when you define terrier, Dog.prototype doesn’t have the numLegs property

you need to create terrier after you finish setting up stuff for Dog

1 Like

Try this after both examples and see if it clears things a bit:

console.log(terrier.__proto__ === Dog.prototype);
1 Like