Problem with creating method in js

<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 the two? Do we usually use the method creation method?

+4
source share
2 answers

Usually you did not add anything to Object.prototype , because then it would be added to everything. This could be used, for example, with "".howSweetAmI() , and that would not make much sense.

Usually 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 a method to a prototype means that all instances use the same method. If you add a method as an instance property, only this instance has this method, and different instances can have different method implementations. For instance:

 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; }; 
+5
source

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

0
source

Source: https://habr.com/ru/post/1486555/


All Articles