1. Factory mode
functionCreateperson (name, age, job) {varo =NewObject (); O.name=name; O.age=Age ; O.job=job; O.sayname=function() {alert ( This. Name); }; returno; } varPerson1 = Createperson ("Nicholas", "Software Engineer"); varPerson2 = Createperson ("Greg", "Doctor");
2. Constructor mode
functionPerson (name, age, job) { This. Name =name; This. Age =Age ; This. Job =job; This. Sayname =function() {alert ( This. Name); }; } varPerson1 =NewPerson ("Nicholas", "Software Engineer"); varPerson2 =NewPerson ("Greg", "Doctor"); //different points from the factory model //1. No display of the created object //2. Assigning properties and methods directly to this //3. No Return statement //4. Creating Objects with new //How to use //1. Use as a constructor varperson =NewPerson ("Nicholas", "Software"); Person.sayname ();//Nicholas //2. As a normal function callPerson ("Yellow", "Doctor"); Window.sayname ();//Doctor //3. Called in the scope of another object varo =NewObject (); Person.call (O,"King", "Nurse"); O.sayname ();//King //Cons: Each method is recreated on each instance
3. Prototype mode
functionPerson () {} Person.prototype.name= "Yellowshorts"; Person.prototype.age= 29; Person.prototype.job= "Software"; Person.prototype.sayName=function() {alert ( This. Name); } varPerson1 =NewPerson (); Person1.sayname ();//Yellowshorts varPerson2 =NewPerson (); Person2.sayname ();//YellowshortsAlert (Person1.sayname= = Person2.sayname);//true
JS Create object