The constructor method is very useful, but there is a waste of memory
Functions assigned by prototype are shared by all objects.
Attributes assigned by prototype are independent.-----If you do not modify the attributes, they are shared
If we want all objects to use the same function, it is best to add functions using the prototype method, which saves memory.
example:
//----Constructor Mode
Add an unchanged attribute "type" to the Cat object, and then add a method eat (eating rat). Then, the prototype object Cat becomes the following:
<script>function Cat(name, color) { this.name = name; this.color = color; this.type = "Feat"; this.eat = function () { alert("Eat mouse"); }; }//Generate example: var cat1 = new Cat("Big Hair", "Yellow");var cat2 = new Cat("Eat Er Hair", "Black");alert(cat1.type); //Feat cat1.eat(); //Eat mouse alert(cat1.eat == cat2.eat); //False</script>That is, for each instance object, the type attribute and the eat() method are exactly the same content. Every time an instance is generated, it must be repeated content and occupy more memory. This is neither environmentally friendly nor efficient.
//----Prototype mode
Javascript stipulates that each constructor has a prototype attribute pointing to another object. All properties and methods of this object will be inherited by instances of the constructor.
This means that we can directly define those unchanged properties and methods on the prototype object.
<script>function Cat(name, color) { this.name = name; this.color = color; }Cat.prototype.type = "Female";Cat.prototype.eat = function () { alert("Eat mouse")};//Generate an instance. var cat1 = new Cat("big hair", "yellow");var cat2 = new Cat("2 hair", "black");alert(cat1.type); // cat cat1.eat();// eating mouse alert(cat1.eat == cat2.eat);//trueF</script>At this time, the type attributes and eat() methods of all instances are actually a memory address, pointing to the prototype object, thus improving the operation efficiency.
The above introduction to the difference between JS constructor and prototype prototype is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.