Javascript implementation methods

Source: Internet
Author: User
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 ;
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.