First, the factory model
functioncreatestudent (name,age) {varo=NewObject (); O.name=name; O.age=Age ; O.myname=function() {alert ( This. Name); }; returno; } varStudent1 =createstudent (' Yjj ', 15); varStudent2 = createstudent (' FFF ', 18);//problem: Factory mode does not solve object recognition problems and cannot determine the type of an objectSecond, the structural function mode
functionStudent (name,age) { This. name=name; This. age=Age ; This. myname=function() {alert ( This. Name); }; } varStudent1_ =NewStudent (' Yjj ', 15); varStudent2_ =NewStudent (' FFF ', 18); //the role of the New keyword //1. Create an Object //2. Assign the scope of the constructor to the new object, which points to the new object //3. Execute the code in the constructor, add the familiar to the new object //4. Returning new objects //problem: Each method is recreated on each instanceThird, constructor mode + prototype mode
function Student (name,age) { this. name=name; this. age= age; } Student.prototype.myName=function() { alert (this. Name); }; varnew Student (' yjj ',N); var New Student (' FFF ',); Student1__.myname ();
Four, dynamic prototype mode
functionStudent (name,age) { This. name=name; This. age=Age ; if(typeof This. myname!= "function") {//First time entryStudent.prototype.myname=function() {alert ( This. Name); }; } } varstudent1___ =NewStudent (' Yjj ', 15); Student1___.myname ();V. Parasitic structural function patterns
functionStudent (name,age) {varo =NewObject (); O.name=name; O.age=Age ; O.myname=function() {alert ( This. Name); }; returno; } varstudent1____ =NewStudent (' Yjj ', 15); Student1____.myname (); //The basic idea of this pattern is to create a function that simply encapsulates the code that creates the object and then returns the newly created object. Six, the SAFE structure function pattern
functionStudent (name,age) {varo =NewObject (); varName=name; varAge=Age ; O.myname=function() {alert (name); }; returno; } varstudent1_____ =NewStudent (' Yjj ', 15); Student1_____.myname (); //no public properties, and other methods do not have to refer to this object
JS create objects in several ways