Constructor
Copy codeThe Code is as follows:
Function coder ()
{
This. name = 'modern magic ';
This. job = 'web developer ';
This. coding = function ()
{Alert ('Code I am writing ');}
}
Var coder = new coder ();
Alert (coder. name );
Coder. coding ();
Factory method
Copy codeThe Code is as follows:
Function createCoderFactory ()
{
Var obj = new Object ();
Obj. name = 'modern magic ';
Obj. job = 'programmer ';
Obj. coding = function ()
{
Alert ('Code I am writing ');
};
Return obj;
}
Var coder = createCoderFactory ();
Alert (coder. name );
Coder. coding ();
Both the factory method and constructor method share the same disadvantage, that is, every function of this class is instantiated every time an instance is created.
Prototype chain
Copy codeThe Code is as follows:
Function coder (){}
Coder. prototype. name = 'modern magine ';
Coder. prototype. job = 'programmer ';
Coder. prototype. coding = function (){
Alert ('Code I am writing ');
};
Var coder = new coder ();
Alert (coder. name );
Coder. coding ();
The disadvantage of a prototype chain is that all its attributes are shared, and all other attributes of an instance will be changed as long as one instance changes. For example:
Copy codeThe Code is as follows:
Var coder1 = new coder ();
Var coder2 = new coder ();
Alert (coder1.name);/* display modern magic */
Coder2.name = 'nowamagic ';
Alert (coder1.name);/* display nowamagic */
Alert (coder2.name);/* This also displays nowamagic */
Hybrid mode
The above three methods all have their own shortcomings, so we need to improve them.
Copy codeThe Code is as follows:
Function coder ()
{
This. name = 'modern magic ';
This. job = 'programmer ';
}
Coder. prototype. coding = function (){
Alert ('Code I am writing ');
};
Dynamic original chain
There is another way to solve the first three shortcomings.
Copy codeThe Code is as follows:
Function coder ()
{
This. name = 'modern magic ';
This. job = 'programmer ';
If (typeof (coder. _ init) = 'undefined ')
{
This. coding = function ()
{
Alert ('Code I am writing ');
};
This. _ init = true;
}
}