DEV Community

loading...

Changing the Prototype to a New Object

Randy Rivera
Once I truly put my mind on something, I won't ever stop.
・1 min read
  • Up until now you have been adding properties to the prototype individually:
Dog.prototype.numLegs = 4;
Enter fullscreen mode Exit fullscreen mode
  • This becomes tedious after more than a few properties.
Dog.prototype.eat = function() {
  console.log("nom nom nom");
}

Dog.prototype.describe = function() {
  console.log("My name is " + this.name + ".");
}
Enter fullscreen mode Exit fullscreen mode
  • A more efficient way is to set the prototype to a new object that already contains the properties. This way, the properties are added all at once:
Dog.prototype = {
  numLegs: 4,
  eat: function() {
    console.log("nom nom nom");
  },
  describe: function() {
    console.log("My name is " + this.name + ".")
  }
};
Enter fullscreen mode Exit fullscreen mode

Remember to Set the Constructor Property when Changing the Prototype

  • There is one crucial side effect of manually setting the prototype to a new object. It erases the constructor property! This property can be used to check which constructor function created the instance, but since the property has been overwritten, it now gives false results:
  • To fix this, whenever a prototype is manually set to a new object, remember to define the constructor property:
function Dog(name) {
  this.name = name;
}

Dog.prototype = {
  constructor: Dog, // <----
  numLegs: 4,
  eat: function() {
    console.log("nom nom nom");
  },
  describe: function() {
    console.log("My name is " + this.name);
  }
};
Enter fullscreen mode Exit fullscreen mode

Discussion (0)