Although prototype-based creation can effectively complete encapsulation, the following problems still exist:
1. Unable to set the attribute value through the constructor
2. When there is a reference type variable in the property, there may be duplicate variable values
Function Person (){
}
Person. prototype = {
Constructor: Person,
Name: "Leon ",
Age: 30,
Friends: ["Ada", "Chris"],
Say: function (){
Alert (this. name + "[" + this. friends + "]");
}
}
Var p1 = new Person ();
P1.name = "John ";
P1.say (); // John [Ada, Chris]
Var p2 = new Person ();
P2.say (); // Leon [Ada, Chris]
P1.friends. push ("Mike ");
// Now there is another Mike in the prototype, which is the second problem caused by the prototype.
P2.say (); // Leon [Ada, Chris, Mike]
/** To solve the problems caused by the prototype, we can create objects by combining constructors and prototypes.
* Define attributes in the constructor and define methods in the prototype.
*/
Function Person (name, age, friends ){
// Attribute defined in Constructor
This. name = name;
This. age = age;
This. friends = friends;
}
Person. prototype = {
Constructor: Person,
// Define the method in the prototype
Say: function (){
Alert (this. name + "[" + this. friends + "]");
}
}
// All attributes are saved in your own space.
Var p1 = new Person ("Leon", 23, ["Ada", "Chris"]);
P1.name = "John ";
P1.friends. push ("Mike ");
P1.say (); // John [Ada, Chris, Mike]
Var p2 = new Person ("Ada", 33, ["Leon"]);
P2.say (); // Ada [Leon]
In order to make the definition method more in line with Java requirements, we place the prototype code of the definition method in the Person constructor.
Function Person (name, age, friends ){
// Attribute defined in Constructor
This. name = name;
This. age = age;
This. friends = friends;
// The definition cannot be rewritten.
/* Person. prototype = {
Constructor: Person,
// Define the method in the prototype
Say: function (){
Alert (this. name + "[" + this. friends + "]");
}
}*/
If (typeof Person. prototype. say ){
// But this will also cause a problem: every new object is defined once in the say method, so we need to add the if condition above.
Person. prototype. say = function (){
Alert (this. name + "[" + this. friends + "]");
}
}
}
Original article reprinted, please indicate the source, this article first in the csdn Website: http://blog.csdn.net/magneto7/article/details/24934149