//Ultimate Edition: Combining the constructor pattern with the prototype mode: *****************************//Evaluation: Set constructor pattern and prototype pattern: a default pattern for defining reference types functionPerson (name, age, Job) {//constructor to define instance properties This. Name =name; This. Age =Age ; This. Job =job; This. Friends = ["Shelby", "Court"]; } Person.prototype= {//prototype properties are used to define methods and shared propertiesConstructor:person, Sayname:function() {alert ( This. Name); } } varPerson1 =NewPerson ("Nicolas", "Software Engineer"); varPerson2 =NewPerson ("Greg", "Doctor"); Person1.friends.push ("Van"); alert (person1.friends); alert (person2.friends); Alert (Person1.friends===person2.friends); Alert (Person1.sayname= = = Person2.sayname);
Combine the constructor pattern with the prototype pattern:
As shown in the code above, the constructor pattern is used to define the instance properties, whereas the prototype pattern is used to define methods and shared properties. The advantage of this is that each instance will have its own copy of the instance properties, while sharing the use of the method.
Disadvantages of prototype mode : For types that contain reference type properties, when each instantiated object is said, the comparison of the reference properties of each object will be perverted.
Person.prototype ={constructor:person, Name:"Nicholas", Age:29, Job:"Software Engineer", friends: ["Shelby", "Court"], Sayname:function() {alert ( This. Name); } }; varPerson1 =NewPerson (); varPerson2 =NewPerson (); Person1.friends.push ("Van"); alert (person1.friends); alert (person2.friends); Alert (Person1.friends= = = Person2.friends);//true
The last line, when the person1 of the heap and the Friends property of the Person2, returns the almost perfect true , which is contrary to the design intention of the program.
For constructor mode:
Every time I instantiate an object, the method is instantiated once (the function is also an object in ECMAScript), and the result of this behavior is that it is not necessary to create two methods to accomplish the same task, especially when the object is new, very scary!!
A "default" mode used in JavaScript to define reference types