1. Factory mode (Factory)
1 functionCreateperson (name, age, title) {2 varo =NewObject ();3O.name =name;4O,age =Age ;5O.title =title;6O.sayname =function(){7Alert This. Name);8 }9 returno;Ten } One A varPerson1 = Createperson ("Greg", "Doctor"); - varPerson2 = Createperson ("Lisa", "Teacher");
Factory mode does not recognize the type of object.
2. Constructor mode (Constructor)
1 functionPerson (name, age, job) {2 This. Name =name;3 This. Age =Age ;4 This. Job =job;5 This. Sayname =function(){6Alert This. Name);7 }8 }9 varPerson1 =NewPerson ("Nicholas", "Software Engineer");Ten varPerson2 =NewPerson ("Greg", "Doctor");
By convention, constructors should always start with an uppercase letter.
To create a new instance of a person, you must use the new operator.
Person1 and Person2 each hold a different instance of person, both of which have a constructor attribute that points to person:
Alert (Person1.constructor = = person) //truealert (person2.constructor = = person) // True
Constructor problem: All methods in the constructor are recreated on each instance.
Alert (Person1.sayname = = person2.sayname); // false
JS 7 Ways to create objects (i)