functionRen (name,age) { This. name=name; This. age=Age ; This. fa=function() {alert (' I like to eat '); } } varp1=Newren (' W1 ', 20); varP2=Newren (' W2 ', 222); Alert (P1.fa==P2.FA)//falseAlert (P1.FA () ==p2.fa ());//truealert (p1.name==p2.name);//false
You will find
Alert (P1.FA==P2.FA) result is false
New an object, each time the function executes, re-instance to create the same function FA, drag down the efficiency of function execution, at this time we think of the method is not to take FA this way out
function Ren (name,age) { this. name=name; this. age= age; this. fa=fa; } function fa () { alert (this. Name); } var p1=New ren (' W1 ', +); var p2=New ren (' W2 ', 222); P1.fa ();
P2.fa ();
In this way, the external redefinition of a FA function, relative to the previous Ren function, new two objects, is not the call is the same FA method, efficiency is not improved?
But is it not necessary to define global FA at this time? It's not quite right ...
At this time, can you put these public methods in one place?
Great prototype appear, each function has a prototype attribute, which is actually a pointer, always point to an object
What is the purpose of this object? ---to include specific properties and methods, and act as a share of all instances
functionRen () {}varobj=Ren.prototype; //alert (obj.constructor);Obj.name= ' Wednesday '; Obj.age=20; OBJ.FA=function() {alert ( This. Name); }; varp1=Newren (' W ', 20); varP2=NewRen (); alert (p1.name); Alert (P1.fa==P2.FA);//trueP1.fa ();
Alert (Obj.isprototypeof (p1));//true
At this point we found that the P1.FA==P2.FA result is true, OK, OK, this time instantiate the object, get a method only once
Here is the prototype legend!
The relationship of constructors, prototype objects, instance objects
Constructor. Prototype= Prototype Object
Prototype object. constructor= Constructors
alert (obj.constructor);
The instance object. Prototype= Prototype Object
Alert (P1.prototype)
Prototype----------prototype detailed answers