A summary of six patterns of JavaScript inheritance _javascript tips

Source: Internet
Author: User
Tags shallow copy

1. Prototype chain

function supertype () {
this.property = true;
}

SuperType.prototype.getSuperValue = function () {return
this.property;
};
Function subtype () {
this.subproperty = false;
}
Inherited the supertype
subtype.prototype = new Supertype ();
SubType.prototype.getSubValue = function () {return
this.subproperty;
};
var instance = new Subtype ();
Alert (Instance.getsupervalue ()); True

The essence of implementation is to rewrite the prototype object and replace it with an instance of a new type.

2. Borrowing constructors

function supertype () {
this.colors = ["Red", "Blue", "green"];
}
Function subtype () {
//Inherits Supertype
Supertype.call (this);
}
var Instance1 = new subtype ();
Instance1.colors.push ("Black");
alert (instance1.colors); "Red,blue,green,black"
var instance2 = new subtype ();
alert (instance2.colors); "Red,blue,green"

If you simply borrow a constructor, you will not be able to avoid the problem of the constructor pattern--the method is defined in the constructor, so the function reuse is not possible. Also, the methods defined in the superclass prototype are also invisible to the subtype, resulting in only the constructor pattern for all types. In view of these problems, the technique of borrowing constructors is rarely used alone.

3. Combined inheritance

function Supertype (name) {
this.name = name;
This.colors = ["Red", "Blue", "green"];
}
SuperType.prototype.sayName = function () {
alert (this.name);

};
Function subtype (name, age) {
//Inheritance Property
Supertype.call (this, name);
This.age = age;
}
Inheritance method
Subtype.prototype = new Supertype ();
SubType.prototype.constructor = subtype;
SubType.prototype.sayAge = function () {
alert (this.age);
};
var Instance1 = new Subtype ("Nicholas");
Instance1.colors.push ("Black");
alert (instance1.colors); "Red,blue,green,black"
instance1.sayname ();//"Nicholas";
Instance1.sayage ();
var instance2 = new Subtype ("Greg");
alert (instance2.colors); "Red,blue,green"
instance2.sayname ();//"Greg";
Instance2.sayage (); 27

In this example, the Supertype constructor defines two properties: name and Colors. Supertype's prototype defines a method Sayname (). The subtype constructor passes in the name parameter when it calls the Supertype constructor, and then its own attribute age is defined. The supertype instance is then assigned to the subtype prototype, and then the method Sayage () is defined on the new prototype. This allows two different subtype instances to have their own properties-including the colors attribute-and the same method.

Combinatorial inheritance avoids the pitfalls of prototype chains and borrowed constructors, and combines their advantages to become the most common inheritance pattern in JavaScript. Furthermore, instanceof and isprototypeof () can also be used to identify objects that are created based on composite inheritance.

4. Prototype inheritance

function Object (o) {
function F () {}
f.prototype = O;
return new F ();
}

Inside the object () function, a temporary constructor is created, then the incoming object is used as the prototype of the constructor, and finally a new instance of the temporary type is returned. Essentially, object () performs a shallow copy of the object passed in. Look at the example below.

var person = {
Name: "Nicholas",
friends: ["Shelby", "Court", "Van"]
};
var Anotherperson = object (person);
Anotherperson.name = "Greg";
AnotherPerson.friends.push ("Rob");
var Yetanotherperson = object (person);
Yetanotherperson.name = "Linda";
YetAnotherPerson.friends.push ("Barbie");
alert (person.friends); "Shelby,court,van,rob,barbie"

This archetypal succession of Rockford advocates requires that you have an object that can be used as the basis for another object. If you have such an object, you can pass it to the object () function, and then modify the resulting object according to the specific requirements. In this example, a person object can be used as the basis for another object, so we pass it into the object () function, and then the function returns a new object. The new object takes the person as a prototype, so its prototype contains a basic type value attribute and a reference type value attribute. This means that Person.friends is not only owned by person, but also shared by Anotherperson and Yetanotherperson. In fact, this is equivalent to creating two copies of the person object.

ECMAScript 5 standardizes prototype inheritance with the new Object.create () method. This method receives two parameters: an object that is used as a prototype of the new object and (optionally) an object that defines additional attributes for the new object. In the case of passing in a parameter, the Object.create () behaves the same as the Object () method.

var person = {
Name: "Nicholas",
friends: ["Shelby", "Court", "Van"]
};
var Anotherperson = object.create (person);
Anotherperson.name = "Greg";
AnotherPerson.friends.push ("Rob");
var Yetanotherperson = object.create (person);
Yetanotherperson.name = "Linda";
YetAnotherPerson.friends.push ("Barbie");
alert (person.friends); "Shelby,court,van,rob,barbie"

The second parameter of the Object.create () method is the same as the second argument of the Object.defineproperties () method: Each property is defined by its own descriptor. Any property specified in this manner overwrites the property with the same name on the prototype object. For example:

var person = {
Name: "Nicholas",
friends: ["Shelby", "Court", "Van"]
};

var Anotherperson = object.create (person, {
name: {
value: "Greg"
}
});
alert (anotherperson.name); "Greg."

Browsers that support the Object.create () method include ie9+, Firefox 4+, Safari 5+, Opera 12+, and Chrome.

Prototype inheritance is perfectly competent in situations where it is not necessary to create a constructor selectmen, but only to keep one object similar to another. Remember, however, that a property that contains a reference type value always shares the corresponding value, just as you would use a prototype pattern.

5. Parasitic inheritance

Parasitic (parasitic) inheritance is a way of thinking that is closely related to archetypal inheritance, and is also Rockford by the Gram-type. The idea of parasitic inheritance is similar to the parasitic constructor and factory pattern, which is to create a function that encapsulates the inheritance process, which in some way enhances the object, and finally, as it does all the work, returns the object. The following code demonstrates the parasitic inheritance pattern.

function Createanother (original) {
var clone = object (original);//Create a new object by calling the functions
Clone.sayhi = Functional () {// In some way to enhance this object
alert ("HI");
return clone; Return this object
}

In this example, the Createanother () function receives an argument, which is the object that will be the base of the new object. The object (original) is then passed to the objects () function to assign the returned result to clone. Add a new Method Sayhi () to the Clone object, and finally return the clone object. You can use the Createanother () function as follows:

var person = {
Name: "Nicholas",
friends: ["Shelby", "Court", "Van"]
};
var Anotherperson = Createanother (person);
Anotherperson.sayhi (); "Hi"

The code in this example returns a new object--anotherperson based on the person. The new object not only has all the properties and methods of person, but also has its own sayhi () method.
Parasitic inheritance is also a useful pattern in situations where objects are primarily considered rather than custom types and constructors. The object () function used in the previous demonstration of inheritance mode is not required, and any function that can return a new object applies to this pattern.

Using parasitic inheritance to add a function to an object can reduce efficiency by not being able to reuse the function;
The point is similar to the constructor pattern.

6. Parasitic Modular inheritance

As mentioned earlier, combined inheritance is the most commonly used inheritance pattern for JavaScript, but it also has its own shortcomings. The biggest problem with combinatorial inheritance is that, in any case, the two-time superclass constructor is invoked: one at a time when a subtype prototype is created, and another within a subtype constructor. Yes, the subtype eventually contains all the instance properties of the superclass object, but we have to override these properties when calling the subtype constructor. Let's take a look at the following examples of combinatorial inheritance.

function Supertype (name) {
this.name = name;
This.colors = ["Red", "Blue", "green"];
}
SuperType.prototype.sayName = function () {
alert (this.name);
};
Function subtype (name, age) {
Supertype.call (this, name);//The second call to Supertype ()
this.age = age;
}
Subtype.prototype = new Supertype (); The first call to Supertype ()
SubType.prototype.constructor = subtype;
SubType.prototype.sayAge = function () {
alert (this.age);
};

The line in bold font is the code that calls the Supertype constructor. The first time the Supertype constructor is invoked, Subtype.prototype gets two properties: name and colors, all of which are instance properties of Supertype, but are now located in the prototype of subtype. When the subtype constructor is invoked, the Supertype constructor is called again, and this time the instance property name and colors are created on the new object. As a result, these two properties mask the two attributes of the same name in the prototype. Figure 6-6 shows the above process.
As shown in Figure 6-6, there are two sets of name and colors properties: One set on the instance and one in the subtype prototype. This is the result of invoking the two-time Supertype constructor. Fortunately we have found a way to solve this problem-parasitic modular inheritance.

The so-called parasitic modular inheritance, that is, by borrowing the constructor to inherit the property, through the prototype chain of the hybrid form to inherit the method. The basic idea behind it is that you don't have to call a superclass constructor to specify a subtype of the stereotype, all we need is a copy of the superclass prototype. In essence, it is the use of parasitic inheritance to inherit the superclass's prototype, and then assign the result to the subtype's prototype. The basic pattern of parasitic modular inheritance is shown below.

function Inheritprototype (subtype, supertype) {
var prototype = object (supertype.prototype);//Create Objects
Prototype.constructor = subtype; Enhanced Object
Subtype.prototype = prototype;//Specify Object
}

The Inheritprototype () function In this example implements the simplest form of parasitic modular inheritance. This function receives two parameters: the subtype constructor and the super type constructor. Inside the function, the first step is to create a copy of the superclass prototype. The second step is to add the constructor property to the replica you created to compensate for the default constructor property that was lost by overriding the stereotype. The final step is to assign the newly created object (that is, a copy) to the prototype of the subtype. In this way, we can use the statement that calls the Inherit-prototype () function to replace the statement that was assigned to the subtype prototype in the previous example, such as

function Supertype (name) {
this.name = name;
This.colors = ["Red", "Blue", "green"];
}
SuperType.prototype.sayName = function () {
alert (this.name);
};
Function subtype (name, age) {
Supertype.call (this, name);
This.age = age;
}
Inheritprototype (subtype, supertype);
SubType.prototype.sayAge = function () {
alert (this.age);
};

The efficient embodiment of this example is that it calls only one supertype constructor at a time, and therefore avoids creating unnecessary, superfluous attributes on the subtype.prototype. At the same time, the prototype chain can remain unchanged, so that instanceof and isprototypeof () can be used normally. It is generally accepted by developers that parasitic combined inheritance is the most ideal inheritance paradigm for reference types.

YUI's YAHOO.lang.extend () method adopted a parasitic combination inheritance, so that this model for the first time in a very wide application of JavaScript library. To learn more about Yui, please visit http://developer. yahoo.com/yui/.

The above is the full content of this article, I hope to learn from JavaScript inheritance to help.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.