Six ways to implement inheritance in JavaScript

Source: Internet
Author: User
Tags shallow copy

Description of the inheritance in javascript:

Many object-oriented languages support two ways of inheriting: interface inheritance and implementation inheritance. Interface inheritance inherits only the method signature, while implementing inheritance inherits the actual method. In JavaScript, because the function does not have a signature, it cannot implement the interface inheritance, but only the implementation of inheritance, and the implementation of inheritance is mainly through the prototype chain to achieve.

First quote the Official document description of the prototype chain: The basic idea is to use the prototype to let one reference type inherit the properties and methods of another reference type. To understand this concept, it is necessary to first clarify the relationship between constructors, prototypes, and instances: each constructor (as long as a function) has a prototype property that points to an object (which is the prototype object of the constructor); A prototype object (as long as the object) has a constructor The property points to a constructor, and the instance contains an internal pointer to the prototype object [[Prototype]]. To put it bluntly, the prototype chain is constructed by assigning an instance of one type to the prototype of another constructor. This way the type can access all of the properties and methods defined on the super-type. Each object has its own prototype object that inherits properties and methods from the prototype object as a template, and the prototype object can have its own prototype and inherit properties and methods from it, one layer at a level, and so on, which is called the prototype chain. It explains why an object has properties and methods that are defined on other objects.


There are six ways in which you implement inheritance in javascript:

1. Prototype chain

2. Borrowing the constructor function

3. Combination inheritance (combined use of prototype chain and borrowing constructors)

4. prototype-Type Inheritance

5. Parasitic inheritance

6. Parasitic combined inheritance (combined use of combination inheritance and parasitic inheritance)

1. Prototype chain

Specific examples:
A basic model for realizing the prototype chain
function Supertype () {
This.property = true;
}
SuperType.prototype.getSuperValue = function () {
return this.property;
};
Function subtype () {
This.subproperty = false;
}

inheritance, using an instance of the Supertype type to override the prototype object of the subtype type
Subtype.prototype = new Supertype ();
SubType.prototype.getSubValue = function () {
return this.subproperty;
};
var instance = new Subtype ();
Alert (Instance.getsupervalue ()); True
Ps:subtype inherits Supertype, and inheritance is achieved by creating an instance of supertype and assigning the instance to subtype's prototype. The essence of implementation is to rewrite the prototype object of the subtype and replace it with an instance of a new type. The new prototype object of the subtype has an internal property [[[Prototype]] pointing to the prototype of Supertype, and a property inherited from the Supertype prototype constructor points to the Supertype constructor. The final prototype chain is this: instance points to Subtype's prototype, subtype's prototype points to Supertype's prototype, and Supertype's prototype points to the prototype of object (the default prototype for all functions is an instance of object, so the default prototype will contain an internal pointer to Object.prototype).
Disadvantages of the prototype chain:
1. When you implement inheritance through a prototype, the prototype will actually become an instance of another type. As a result, the original instance attribute is logically transformed into the current prototype attribute and is shared by all instances. It is understood that an instance property of a reference type value defined in a superclass constructor will become a prototype attribute on a subtype prototype that is shared by all child type instances.
2. When you create an instance of a subtype, you cannot pass parameters to the constructor of the superclass type.

2. Borrowing constructors (also known as forged objects or classic inheritance)

Specific examples:
Call the Supertype constructor inside the subtype constructor, and use the Apply () or call () method to bind the parent object's constructor to the child object
function Supertype () {
Defining reference Type Value properties
This.colors = ["Red", "green", "blue"];
}
Function subtype () {
Inherit Supertype, where you can also pass parameters to the superclass constructor
Supertype.call (this);
}
var Instance1 = new subtype ();
Instance1.colors.push ("purple");
alert (instance1.colors); "Red,green,blue,purple"

var instance2 = new subtype ();
alert (instance2.colors); "Red,green,blue"
PS: By using the Apply () or call () method, we are actually invoking the Supertype constructor in the context of the subtype instance that will be created. In this way, all the object initialization code defined in the Supertype () function is executed on the new subtype object. As a result, each instance of subtype will have its own copy of the Colors property.
The advantage of borrowing a constructor is that it solves two problems of the inheritance of the prototype chain implementation, and the disadvantage of borrowing the constructor is that the method is defined in the constructor, so the function reuse cannot be implemented. Also, methods defined in a super-type prototype are not visible to the subtypes, and all types can only use the constructor pattern.

3. Combination inheritance (also known as pseudo-classical inheritance)

Specific examples:
Combine the prototype chain and the technology that borrows the constructor into one piece. Use the prototype chain to implement inheritance of prototype properties and methods, and to implement inheritance of instance properties by borrowing constructors. This enables the reuse of functions by defining methods on the prototype, and ensures that each instance has its own properties.
function Supertype (name) {
THIS.name = name;
This.colors = ["Red", "green", "blue"];
}
SuperType.prototype.sayName = function () {
alert (this.name);
};
Function subtype (name,age) {
Inheriting properties by borrowing constructors
Supertype.call (This,name);
This.age = age;
}
Method of inheritance of prototype chain mode
Subtype.prototype = new Supertype ();
SubType.prototype.constructor = subtype;
SubType.prototype.sayAge = function () {
alert (this.age);
};
var Instance1 = new Subtype ("Luochen", 22);
Instance1.colors.push ("purple");
alert (instance1.colors); "Red,green,blue,purple"
Instance1.sayname ();
Instance1.sayage ();

var instance2 = new Subtype ("Tom", 34);
alert (instance2.colors); "Red,green,blue"
Instance2.sayname ();
Instance2.sayage ();
PS: Combinatorial inheritance avoids the defects of prototype chains and borrowing constructors, and blends their advantages into the most commonly used inheritance patterns in JavaScript. Furthermore, using the instanceof operator and the Isprototype () method can also be used to identify objects that are created based on composite inheritance. However, it also has its own shortcomings. The biggest problem is that no matter what the situation, the two-time superclass constructor is called: one time when a subtype prototype is created, and the other is inside the subtype constructor.

4. prototype-Type Inheritance

Specific examples:
Prototypes allow you to create new objects based on existing objects without having to create custom types.
1. Customizing a function to achieve prototype inheritance
function Object (o) {
function F () {}
F.prototype = O;
return new F ();
}
PS: Inside the object () function, create a temporary constructor, then use the incoming object as a prototype of this constructor, and finally return a new instance of the temporary type. Essentially, object () performs a shallow copy of the object passed in.
2, the use of Object.create () method to achieve the prototype-type inheritance. This method receives two parameters: one is the object used as the prototype of the new object and an object that defines additional properties for the new object. This method acts in the same way as the object () method in the case of passing in a parameter.
In the case of passing in the second argument, any property specified will overwrite the same name property on the prototype object.
var person = {
Name: "Luochen",
Colors: ["Red", "green", "blue"]
};
var anotherPerson1 = object.create (person,{
Name: {
Value: "Tom"
}
});
var anotherPerson2 = object.create (person,{
Name: {
Value: "Jerry"
}
});
AnotherPerson1.colors.push ("purple");
alert (anotherperson1.name); "Tom"
alert (anotherperson2.name); "Jerry"
alert (anotherperson1.colors); "Red,green,blue,purple"
alert (anotherperson2.colors); "Red,green,bule,purple";
PS: In cases where one object is similar to another object, prototype inheritance is perfectly capable. However, the disadvantage is that properties that contain reference type values will always share the corresponding values.

5. Parasitic inheritance

 specific example: 
//creates a function that encapsulates the inheritance process internally, which in some way enhances the object, and finally returns the object
function Createperson ( Original) {
           var clone = Object.create (original);  /through Object.create () function to create a new object
           clone.saygood = function () {          &NBS P  //enhanced This object
                       alert ("Hello world! !! ");
           };
           return clone,                                      //returns this object
}
p S: Parasitic inheritance is also a useful pattern in situations where objects are primarily considered rather than custom types and constructors. The disadvantage of this pattern is that function reuse is not done.

6. Parasitic combined inheritance

Specific examples:
By borrowing constructors to inherit attributes, the method is inherited through the compositing form of the prototype chain. Essentially, a parasitic inheritance is used to inherit a super-type prototype, and then the result is assigned to the child type's prototype
function Supertype (name) {
THIS.name = name;
This.colors = ["Red", "green", "blue"];
}
SuperType.prototype.sayName = function () {
alert (this.name);
};
Function subtype (name,age) {
Supertype.call (This,name);
This.age = age;
}
Create a copy of a super-type prototype
var anotherprototype = object.create (Supertype.prototype);
Resetting the default constructor property lost due to rewriting a prototype
Anotherprototype.constructor = subtype;
To assign a newly created object to a prototype of a subtype
Subtype.prototype = Anotherprototype;

SubType.prototype.sayAge = function () {
alert (this.age);
};
var Instance1 = new Subtype ("Luochen", 22);
Instance1.colors.push ("purple");
alert (instance1.colors); "Red,green,blue,purple"
Instance1.sayname ();
Instance1.sayage ();

var instance2 = new Subtype ("Tom", 34);
alert (instance2.colors); "Red,green,blue"
Instance2.sayname ();
Instance2.sayage ();
PS: The efficient embodiment of this example is that it calls only once the Supertype constructor, and therefore avoids creating unnecessary, unnecessary properties on the Subtype.prototype. At the same time, the prototype chain remains intact, so the instance operator and the Isprototype () method can be used normally.





This article from "Luo Chen's Blog" blog, reproduced please contact the author!

Six ways to implement inheritance in JavaScript

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.