Seven modes for JavaScript to create objects

Source: Internet
Author: User

1. Factory mode

1 functionCreateperson (name,age) {2        varobj =NewObject ();3Obj.name =name;4Obj.age =Age ;5        functionSayname () {6 alert (obj.name);7        };8 sayname ();9        returnobj;Ten    } One     varperson = Createperson ("Wutian", 22);

2. Constructor mode

1 functionPerson (name,age) {2         This. Name =name;3         This. Age =Age ;4        functionSayname () {5Alert This. Name);6        };7 sayname ();8    }9     varperson = person ("Wutian", 22);

By convention, constructors should always start with an uppercase letter, which takes four steps:

Constructs a new object, assigns the scope of the constructor to the new object, execute constructor code, and returns the new object

3. Prototype mode

1 functionPerson () {2 3     }4Person.prototype.name = "Wutian";5Person.prototype.age = 22;6Person.prototype.sayName =function(){7Alert This. Name);8     }9     varPerson1 =NewPerson ();Ten     varPerson2 =NewPerson (); OneAlert (Person1.name = = = Person2.name);//true

Description Person1 and Person2 are accessing the same name

4. Combination of constructor mode and prototype mode

1  functionPerson (name,age) {2          This. Name =name;3          This. Age =Age ;4     }5Person.prototype= {6Sayname:function(){7Alert This. Name);8             }9     }Ten     varPerson1 =NewPerson (' Wu ', 22); One     varPerson2 =NewPerson (' Wu ', 22); A alert (person1.name); -Alert (Person1 = = = Person2);//false -Alert (Person1.sayname = = = Person2.sayname);//true

5. Dynamic prototype mode

1  functionPerson (name,age) {2          This. Name =name;3          This. Age =Age ;4         if(typeof  This. sayname! = "function"){5Person.prototype.sayName =function () {6Alert This. name);//Create a function if the Sayname method does not exist7             }8         }9     }Ten     varPerson1 =NewPerson (' Wu ', 22); OnePerson1.sayname ();

6. Parasitic structural function mode

Seven modes for JavaScript to create objects

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.