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