functionFoo () {}foo.prototype.sayname=function(){ return' Initial prototype ';}varFoo1 =NewFoo (); Foo1.sayname ()//' initial prototype '
New way to rewrite the prototype;functionBar () {}foo.prototype=NewBar ();//varFoo2 =NewFoo (); Foo2.sayname ();//error is not found in this method.Bar.prototype.sayName=function(){ return' Prototype of the first rewrite ';}varFoo3 =NewFoo (); Foo3.sayname ()//' prototype of the first rewrite '//overrides the method defined after rewriting the prototypeFoo.prototype.sayName =function(){ return' A way to cover a new prototype '}varFoo4 =NewFoo (); Foo4.sayname ()//' A way to cover a new prototype '//The method of overwriting the prototype does not affect other instances calling this method;//Other instances will also continue to call (before overwriting) the original methodvarBar =NewBar (); Bar.sayname ()//' prototype of the first rewrite '//object literal overrides the prototype object; The connection between the new instance and the original prototype is severed.Foo.prototype ={getheight:function(){ return' Height is 2m '}, Getweight:function(){ return' Weight is 1kg ' }}//equivalent to Foo.property = new Object (), and then define the method ...varFoo5 =NewFoo (); Foo5.sayname ()//error is not found in this method.//But the original example could still be connected to the original prototype.Foo4.sayname ()//' A way to cover a new prototype 'foo.prototype.__proto__= = Object.prototype//true//In addition, the properties defined in the constructor function are better understood, and there are not so many changes .
The experience of prototype is mainly to judge whether the instance is defined before rewriting the prototype, or after rewriting the prototype ;
- 1. Rewriting the prototype will disconnect the original instance from the existing prototype
- 2. Rewriting the prototype will disconnect the existing instance from the original prototype
Remember a word
- The pointers in the instance point only to the prototype, not to the constructor
JavaScript prototype prototype use experience