Creating objects
First type: Object-based
var New = ' My Name '=function() { returnthis. Name;}
Second: The object literal way (a more clear Lookup object contains the properties and methods)
var person = { ' My name ', +, function() { return This . Name;} }
Objects can be created using the object constructor or object literal, but the disadvantage is that when you create multiple objects, there is a lot of duplicate code, so here's how to create an object that solves the problem
1. Factory mode
functionCreateperson (name, age) {varo =NewObject (); O.name=name; O.age=Age ; O.getage=function () { return This. Age; }; returno;}varperson = Createperson (' Zhang San ', 23); Console.log (Person.name); //' Zhang San 'console.log (person.age); //23Console.log (Person.getage ()); //23
Cons: Creating objects is given to a factory method to implement and can pass parameters, but the main disadvantage is that the object type cannot be recognized because the created object is done using the native constructor of object.
2. Constructor mode
function person (name, age) { this . Name = name; this . Age = age; this . Getage = function () { return this .age; };} var person = new person (' Zhang San ', 23//' Zhang San ' console.log (person.age); //23 console.log (Person.getage ()); //23
Alert (person instanceof person); //true;
Alert (person instanceof Object); //true;
Define the properties and methods of the object type (for example, person) by using a custom constructor (just like a normal function, which is used only to create objects). It differs from the factory approach in that:
- Object not explicitly created
- Assigning properties and methods directly to the This object;
- no return statement;
In addition, to create an instance of person, you must use the New keyword, with the person function as the constructor, passing parameters to complete the object creation;
function Person (name, age) { this. Name = name; this. Age = Age ; this. getage = new Function ("Return this.age"); Same as above, multiple functions are created repeatedly}
Cons: The code above, when creating multiple instances, calls new function () repeatedly, creating multiple instances of the function that are not in a scope , and of course, this is not a mistake, but it can cause memory waste.
3. Prototype mode
function person (name) { this.name ==function () { Returnthis. age;}; var New Person (' Zhang San '); Console.log (Person.name); ' Zhang San ' console.log (person.age); 23console.log (Person.getage ()); at
JS each function has a prototype (prototype) attribute, which is a pointer to an object, which is the prototype object for all instances created with the function using the new operator .
The most important feature of a prototype object is that all object instances share the properties and methods it contains, that is, all properties or methods created in the prototype object are shared directly by all object instances.
The access procedure for an instance property or method is a search process:
- First, start with the object instance itself, and return the property value directly if it is found;
- If the instance itself does not exist to find the attribute, continue searching for the prototype object pointed to by the pointer, in which to find the property of the given name, and return if there is one;
Based on the above analysis, the prototype schema creates an object instance whose properties are shared with the prototype object, but can be defined in its own instance, not from the prototype object when it is searched, but rather by the search principle, which is the property in the instance that masks the properties in the prototype object;
You can use the hasOwnProperty () method to determine whether the property is the instance itself or the prototype.
Person.hasownproperty ("name"); // true Person.hasownproperty ("Age"); // false
Cons: The most important thing is that when an object's property is a reference type, its value is constant, always referencing the same external object, and any changes that occur to that object anywhere in the instance will cause changes in other instances.
function person (name) { this. Name== =[' Red ', ' yellow 'var New person (' Zhang San '); Console.log (Person1.name); ' Zhang San ' console.log (Person1.color); //["Red", "yellow"]person1.color.push (' black '); varnew person (' John Doe '); Console.log (Person2.name); ' John Doe '
Console.log (Person2.color); //["Red", "yellow", "black"]//person1 's modifications affected the Person2
4. Combined use of constructor mode and prototype mode
The most commonly used definition type method is the combination of the constructor pattern and the prototype pattern.
The constructor pattern is used to define the properties of the instance, whereas the prototype pattern is used to define methods and shared properties. as a result, each instance will have its own copy of the instance properties, but at the same time share a reference to the other method, maximizing memory savings.
In addition, the combination mode supports passing parameters to the constructor, which is the director of the two family.
functionPerson (name, age) { This. Name =name; This. Age =Age ; This. color = [' red ', ' yellow '];} Person.prototype={Constructor:person, //prototype literal form will change the object's constructor, and also force the person to refer back to the person; Getage:function () { return This. Age; }};varPerson1 =NewPerson (' Zhang San ', 23);p Erson1.color.push (' Black '); Console.log (Person1.name); Zhang San Console.log (Person1.color); //["Red", "yellow", "black"]Console.log (Person1.getage ()); atvarPerson2 =NewPerson (' John Doe ', 24); Console.log (Person2.name); John Doe Console.log (Person2.color); //[' red ', ' yellow '] console.log (Person2.getage ()); -
5. Dynamic prototype mode
The instance properties in the composition mode are separated from the shared method (defined by the prototype), which is not consistent with the pure object-oriented language, and the dynamic prototype pattern encapsulates all the construction information in the constructor and preserves the advantages of the combination. The principle is to determine whether a shared method or property has been defined in the prototype of the constructor, and if not, the definition process is no longer performed. The method is only defined once on the prototype, and all construction procedures are encapsulated in the constructor, and modifications to the prototype are immediately reflected in all instances:
functionPerson (name, age, job) { This. Name =name; This. Age =Age ; This. Job =job; This. lessons = [' Math ', ' Physics '];}if(typeof This. GetName = ' function ') {//by judging instance encapsulationPerson.prototype ={Constructor:person,//The prototype literal method changes the object's constructor into object and also forces the person to refer back to the personGetName:function() {return This. Name; }}}varPerson1 =NewPerson (' Jack ', ' software engneer ');p Erson1.lessons.push (' Biology ');varPerson2 =NewPerson (' Lily ', mechanical, ' Engneer '); alert (person1.lessons);//math,physics,biologyalert (person2.lessons);//Math,physicsAlert (Person1.getname = = = Person2.getname);//true,//defining methods in shared prototypes
JavaScript Object-oriented (multiple ways to create objects)