This article mainly refers to Nanyi's Javascript object-oriented programming (a): encapsulation
1. Original method (also the simplest method)
1 var p1 = {}; 2 var New Object ();
The two lines of code above have the same effect.
1 var p1 = {}; 2 p1.name = ' Zhang San '; 3 p1.age =; 4 5 var p2 = {}; 6 p2.name = ' cui Hua '; 7 p2.age = 18;
2. Original method Upgrade version
1 function Person (name, age) {2 return {3 name:name,4 age:age5 } 6}7var p1 = person (' Zhang San ',%); 8 var p2 = person (' Cui Hua ', 18);
The object created by this method has no connection, its nature and Method 1 are no different.
3. Constructor mode (use this)
1 function Person (name, age) {2 this. Name = name; 3 this. Age = Age ; 4 }5varnew person (' Zhang San ', +); 6 var New Person (' Cui Hua ', 18);
The constructor property of the preceding code instance points to their constructor.
1 // true 2 // true 3 4 instanceof // true 5 instanceof // true
and verify with instanceof that it is indeed an instance of person.
Problems with the construction method
1 functionPerson (name, age) {2 This. Name =name;3 This. Age =Age ;4 This. Takebus =function() {5Alert (' Take a bus. '));6 }7 }8 varP1 =NewPerson (' Zhang San ', 23);9 varP2 =NewPerson (' Cui Hua ', 18);
After adding a "Takebus" method to the above method, the surface looks fine, but:
1 // false
P1 and P2 respectively have a "Takebus" this method, that is, "Takebus" This method is not common. Cause waste of resources. So how is it common?
4. Prototype mode
1 functionPerson (name, age) {2 This. Name =name;3 This. Age =Age ;4 }5 6Person.prototype.takeBus =function() {7Alert (' Take a bus. '));8 }9 Ten varP1 =NewPerson (' Zhang San ', 23); One varP2 =NewPerson (' Cui Hua ', 18); A -P1.takebus = = P2.takebus//true
You can see that using prototype this way, the object "Takebus" method that "person" instantiates gets is the same method.
How JavaScript Creates objects