Up until now you have been adding properties to the prototype individually:
Dog.prototype.numLegs = 4;
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 + ".");
}
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 + ".")
}
};
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);
}
};
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)