First, careful analysis of the previous prototype mode to create the object method, found that the prototype schema creation object, there are some problems, as follows:
1, it omitted to pass the initialization parameter for the constructor function this link, the result all instances will obtain the same attribute value in the default situation, this is not the biggest problem!
2, the biggest problem is that all the attributes in the prototype are shared by many instances, which is appropriate for the function, and for those that contain the base value, because we know that you can add a property of the same name on the instance, you can hide the corresponding property in the prototype. However, for attributes that contain the value of the application type, the problem is very serious and the code is as follows:
functionPerson () {}person.prototype={constructor:person, Name:"Zhang San", Age:22, Job:"Coder", friends:["John Doe", "Harry"], Sayname:function() {alert ( This. Name); }}varperson1=NewPerson ();varPerson2=NewPerson ();p Erson1.friends.push ("Zhao Liu"); alert (person1.friends); //output: John Doe, Harry, Zhao Liualert (person2.friends);//output: John Doe, Harry, Zhao Liu
Analyzing the code above, when we add a friend for Person1, we find that Person2 has also been added a friend, but this is not what we want, and this is due to the shared nature of the prototype pattern, as long as any one instance modifies the property value in the Prototype Property object, All instances associated with the prototype object will be affected!
JavaScript Object-oriented learning the problem of creating objects with six prototype patterns, combining the constructor pattern and prototype schema to create objects