The most basic way to create objects is through the object constructor or object literal:
① creates an object in the form of an object constructor:
1 var person=New Object (); or write var person={}2 person.name= ' Zhang San ';
② create objects in the form of object literals:
1 var person={name: ' Zhang San '};
Both the object constructor pattern and the object literal pattern have obvious drawbacks: When creating many objects using the same interface, a lot of duplicate code is generated. To solve this problem, you can use Factory mode. A factory pattern is a function of encapsulating the details of creating objects in a specific interface.
③ Create objects in Factory mode:
1 function Createperson (name,sex) {2 var person={}; 3 Person.name=name; 4 person.sex=sex; 5 return Person ; 6 }78var person=createperson (' Zhang San ', ' Male ');
Factory mode the way that objects are created solves the problem of duplicate code, but there is an important issue to be solved, which is the problem of object recognition, that is, all objects created in Factory mode can only be judged to be of type object and cannot be further recognized by the object. To solve this problem, we can use the constructor pattern.
④ creates an object in a constructor-mode manner:
1 function Person (name,sex) {2 this. name=name; 3 this. sex=sex; 4 }5var p=New person (' Zhang San ', ' Male ');
The way in which objects are created in constructor mode differs from the way in which objects are created in Factory mode: A, created objects that are not displayed, B, properties and methods are paid directly to THIS;C, no return statements. To create an instance of the person at the same time, you must use the new operator. Objects created by means of constructors can determine the type of an object by P.constructor==person or P instanceof person. Although creating an object as a constructor solves the problem of object recognition, there are still some problems, that is, each method is recreated on each instance when the method property exists for that reference type. We can use prototype mode to solve this problem. The prototype pattern is to add properties and methods on the prototype of the constructor, which are shared by all instances of the object generated by the constructor. The advantage of using the prototype pattern is that all object instances can share properties and methods on the prototype object.
⑤ Create objects in prototype mode:
1 functionPerson (name,age) {2 This. name=name;3 This. age=Age ;4 }5 6Object.defineproperty (Person.prototype, ' birth ', {get:function(){7 return((NewDate ()). getFullYear ()- This. age);8 }})9 Ten varp=NewPerson (' Zhang San ', 25); OneConsole.log (P.birth);//1991
JavaScript Learning notes: Creating objects