4
<script>
var mango =  new Object ();
mango.color = "yellow";
mango.shape= "round";
mango.sweetness = 8;
Object.prototype.howSweetAmI = function () {
console.log("Hmm Hmm Good");
}
console.log(mango); 
</script>

Question:

I can change this line: Object.prototype.howSweetAmI to mango.howSweetAmI, and both of them can work. But what is the difference between them? usually we use which way to create method?

user2294256
  • 1,029
  • 1
  • 13
  • 22

2 Answers2

5

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; };
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

Adding a function to the Object prototype will make that function available on every javascript object. (console.log(window.howSweetAmI)). Moving it to mango will make it a property of that single object.

David Hedlund
  • 128,221
  • 31
  • 203
  • 222