Prototype-based creation, while encapsulating effectively, still has the following problems:
1. Unable to set property value by constructor
2. When there is a reference type variable in the attribute, there may be a duplicate value for the variable
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");
There's one more Mike in the prototype, and that's the second problem with the prototype.
P2.say (); Leon[ada,chris,mike]
/** in order to solve the problems caused by the prototype, we can implement the object creation by combining constructors and prototypes.
* Define the attribute in the constructor, define the method in the prototype
*/
function Person (name,age,friends) {
property is defined in the constructor
THIS.name = name;
This.age = age;
This.friends = friends;
}
Person.prototype = {
Constructor:person,
method is defined in the prototype
Say:function () {
Alert (this.name+ "[" +this.friends+ "]");
}
}
At this point all the properties are saved in their 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]
To make the definition more consistent with the Java requirements, place the prototype code of the definition method into the person's constructor
function person (name,age,friends) {
// The
this.name = name is defined in the constructor of the property.
this.age = age;
this.friends = friends;
//cannot define
/*person.prototype = {
constructor by using overrides: person,
//method defined in prototype
say:function () {
alert (this.name+ "[" +this.friends+ "]");
}
}*/
if (typeof Person.prototype.say) {
But this also raises the question: that is, every new object, the say method is defined once so we add the IF condition
person.prototype.say = function () {
alert (this.name+ "[" +this.friends+ "]");
}
}
}
original articles such as reproduced, please specify the source, this article starts on the CSDN website: http://blog.csdn.net/magneto7/article/details/24934149