Constructor
Function Coder ()
{
This . Name = ' Modern magic ' ;
This . Job = ' Web developers ' ;
This . Coding = Function ()
{
Alert ( ' I'm writingCode ' );
}
}
VaR Coder = New Coder ();
Alert (CODER. Name );
Coder. coding ();
Factory method
Function Createcoderfactory ()
{
VaR OBJ = New Object ();
OBJ. Name = ' Modern magic ' ;
OBJ. Job = ' ProgramEmployee ' ;
OBJ. Coding = Function ()
{
Alert ( ' I am writing code ' );
};
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
Function Coder (){}
Coder. Prototype. Name = ' Modern magic ' ;
Coder. Prototype. Job = ' Programmer ' ;
Coder. Prototype. Coding = Function (){
Alert ( ' I am writing code ' );
};
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:
VaR Coder1 = New Coder ();
VaR Coder2 = New Coder ();
Alert (coder1.name ); /* Show modern magic */
Coder2.name = ' Nowamagic ' ;
Alert (coder1.name ); /* Show nowamagic */
Alert (coder2.name ); /* This also shows nowamagic */
Hybrid mode
The above three methods all have their own shortcomings, so we need to improve them.
Function Coder ()
{
This . Name = ' Modern magic ' ;
This . Job = ' Programmer ' ;
}
Coder. Prototype. Coding = Function (){
Alert ( ' I am writing code ' );
};
Dynamic original chain
There is another way to solve the first three shortcomings.
Function Coder ()
{
This . Name = ' Modern magic ' ;
This . Job = ' Programmer ' ;
If ( Typeof (CODER. _ init) = ' Undefined ' )
{
This . Coding = Function ()
{
Alert ( ' I am writing code ' );
};
This . _ Init = True ;
}
}