Factory mode creates objects, although in line with normal thinking.
However, because the object is defined inside the function, it is not possible to know the type of the object (all of them are object).
Using the constructor pattern, you can create a specific type of function instance:
function Dog (age,size) { this.age=age; This.size=size; This.toage=function () { alert (this.age); }; } var dog1=new Dog (10,20); var dog2=new Dog (22,1);
At this point, the above function can be thought of as the constructor of the object.
Example, the property is directly assigned to the This object, and the constructor for creating the object is the same as the constructor, for example:
alert (dog1.constructor==dog);//true
So, what is the type of object you are creating?
Alert (dog1 instanceof Object),//true alert (dog1 instanceof Dog);//true
Yes, the constructor can identify his instance as a specific type of dog type.
and the constructor function as a function, of course, can be called separately:
Called Dog (11,22) as a normal function;//Added to window scope window.toage ();//11//calls var o ={ in the scope of another object; Dog.call (o,11,22); O.toage ();//11
But the constructor above, when generating an instance, actually operates the following code:
function Dog (age,size) { this.age=age; This.size=size; this.toage= New Function ("Alert (this.age)"); }
Obviously, each instance has a function instance.
alert (dog1.toage==dog2.toage);//false
So we can move the function definition outside the constructor.
function Dog (age,size) { this.age=age; This.size=size; this.toage=toage; } function Toage () { alert (this.age); } var dog1=new Dog (11,22); var dog2=new Dog (2,33);
In this case, memory usage is reduced. However, the global function you know ...
JavaScript Builder Pattern Creation object