Usually you would not add anything to Object.prototype
, because then it would be added to everything. It would be usable for example with "".howSweetAmI()
, and that wouldn't make much sense.
Normally you have a specific type where you add methods to the prototype, for example:
function Fruit(color, shape, sweetness) {
this.color = color;
this.shape = shape;
this.sweetness = sweetness;
}
Fruit.prototype.howSweetAmI = function() {
return this.sweetness;
};
var mango = new Fruit("yellow", "round", 8);
Adding the method to the prototype means that all instances uses the same method. If you add a method as a property to the instance, only that instance has the method, and different instances can have different implementations of the method. For example:
var mango = new Fruit("yellow", "round", 8);
var banana = new Fruit("yellow", "bent", 70);
mango.howSweetAmI = function() { return this.sweetness; };
banana.howSweetAmI = function() { return this.sweetness * 0.1; };