Article Introduction: a common way to create custom types is to combine the constructor pattern with the prototype pattern. The constructor pattern is used to define instance properties, which are used to define methods and shared properties. As a result, each instance will have a copy of its own instance attribute. But at the same time also share a reference to the method, the maximum amount of memory savings. In addition, this pattern also supports the construction letter |
A common way to create custom types is to combine the constructor pattern with the prototype pattern. The constructor pattern is used to define instance properties, which are used to define methods and shared properties. As a result, each instance will have a copy of its own instance attribute. But at the same time also share a reference to the method, the maximum amount of memory savings. In addition, the model also supports the transfer of parameters to the constructor, which is the length of the set of two modes. The following code overrides the previous example:
function person (name, age, Job) {
this.name = name;
This.age = age;
This.job = job;
This.friends = ["Shelby", "Court"];
}
Person.prototype = {
Constructor:person,
sayname:function () {
alert (this.name);
}
}
var person1 = new Person ("Nicholas", "Software Engineer");
var person2 = new Person ("Greg", "Doctor");
Person1.friends.push ("Van");
alert (person1.friends); "Shelby,count,van"
alert (person2.friends);//"Shelby,count"
alert (person1.friends = = = Person2.friends ); False
alert (person1.sayname = = person2.sayname);//true
In this example, the instance properties are defined in the constructor, and the property constructor and Method Sayname () shared by all instances are defined in the prototype. The modification of person1.friends () does not affect person2.friends because they refer to different arrays, respectively.
This kind of constructor and prototype blending mode is the most widely used and the most ECMAScript method to create a custom type in the present. It can be said that this is a default mode for defining reference types.