Detailing how JavaScript implements inheritance in several ways (recommended) _javascript tips

Source: Internet
Author: User

ECMAScript only supports implementation inheritance, and its implementation inheritance relies primarily on the prototype chain.

Prototype chain

The basic idea of the prototype chain is to make a reference type inherit the properties and methods of another reference type using the prototype. Each constructor has a prototype object that contains a pointer to the constructor, and the instance contains a pointer to the prototype object. If: We make the prototype object a equal to another instance of type B, then the prototype object A has a pointer to the prototype object of B, and the corresponding B prototype object holds a pointer to its constructor. If B's prototype object is another type of instance, then the relationship is still set up, so layer by layer, it constitutes an example and prototype chain.

The diagram of the instance and the constructor and the prototype is as follows:

Person.constructor now points to parent, because Child.prototype points to the prototype of parent, while the constructor of the parent prototype object points to parent.

When an instance property is accessed in read mode, the property is first searched for in the instance, and if the property is not found, the search for the instance's prototype continues. In the integration implemented through the prototype chain, the search process continues up the prototype chain until the end of the prototype chain is searched.

For example, call the Person.getparentvalue () method, 1) The search instance, 2 search the child.prototype;3) search Parent.prototype, and find the Getparentvalue () method stop.

1, the default prototype

The prototype chain shown in the previous example is less than one link, and all reference types inherit object by default, and this inheritance is implemented through a prototype chain. So the default prototype contains an internal pointer, pointing to Object.prototype, which is the root cause of the default methods that all custom types inherit tostring (), valueof (), and so on. In other words object.prototype is the end of the prototype chain.

2, determine the relationship between the prototype and the case

There are two ways to determine the relationship between a prototype and an instance, the first is to use the instanceof operator, and the second is to use the isPrototypeOf () method.
Instance instanceof The constructor that appears in the prototype chain, returns True

Console.log (person instanceof Child),//true 

console.log (person instanceof Parent);//true 
Console.log ( Person instanceof Object);//true 
Isprototype (), as long as it is a prototype in the prototype chain, can be said to be the prototype of the instance derived from the prototype chain, and therefore returns true. 
Console.log (Object.prototype.isPrototypeOf (instance));//true 
Console.log (Parent.prototype.isPrototypeOf ( instance));//true 

3. Carefully define the method

Subtypes sometimes need to overwrite a method in the superclass, or you need to add a method that does not exist in the superclass, note that the code to add a method to the stereotype must be placed after the statement that replaces the prototype.

When Getparentvalue () is invoked through an instance of a child, the redefined method is invoked, but the original method is invoked when Getparentvalue () is invoked through an instance of parent.

It is particularly important to note that the two methods must be defined after the instance of parent is replaced by the prototype.

It is also important to note that when you implement inheritance through a prototype chain, you cannot use object literals to create a prototype method, because doing so overrides the prototype chain.

The above code just assigns the instance of parent to the prototype object of the child, and then replaces the prototype with a literal, replaced by the literal, the child prototype actually contains an instance of object rather than an instance of parent, so the prototype chain we envision is cut off. There is no association between parent and child.

4, the problem of the prototype chain

The prototype chain is powerful and can be used to implement inheritance, but there are also problems, the main problem is that the stereotype attributes that contain reference type values are shared by all instances. So we define the instance properties in the constructor. But when you implement inheritance through a prototype, the prototype object actually becomes an instance of another type. The instance attribute originally defined in the constructor becomes the prototype property.

Examples are as follows:

A Friends property is defined in the parent constructor, which is an array (reference type value). In this way, each instance of parent will each contain its own friends attribute. When the child inherits the parent through the prototype chain, Child.prototype also uses the Friends attribute-as if the Friends attribute is defined in Child.prototype. All instances of the child will share the Friends attribute, so the changes we make to Kid1.friends are also reflected in kid2.friends, which is obviously not what we want.

Another problem with the prototype chain is that when you create an instance of a subtype, you cannot pass arguments to a superclass constructor without affecting all instances of the object. Therefore, we usually rarely use the prototype chain alone.

Borrowing constructors

In order to solve some problems caused by reference type value in prototype, the technique of borrowing constructors is introduced. The basic idea of this technique is to call the superclass constructor inside the subtype constructor.

Parent.call (this) invokes the parent constructor in the context of the newly created child instance. Invokes the parent constructor in the newly created child instance environment. Thus, on the new child object, the object initialization code defined in the parent () function is executed on the KID1 and Kid2 objects here. In this way, each child instance will have a copy of its own friends attribute.

You can borrow a constructor to pass arguments to a superclass constructor in the constructor of a subtype.

To ensure that a subtype's familiarity is not overridden by the constructor of the parent class, you can add the subtype's properties after calling the parent class constructor.
Problem with constructors:

The problem with the constructor pattern is that the methods are defined in the constructor and the function multiplexing is not available, so the pattern of borrowing constructors is rarely used alone.

Combined inheritance

Combinatorial inheritance refers to the combination of a prototype chain and a technology that borrows a constructor to play both. That is, using the prototype chain to implement the inheritance of the prototype properties and methods, and by borrowing the constructor to implement the inheritance of the instance properties.


The person constructor defines two properties: name and friends. The person's prototype defines a method Sayname (). When invoking the parent constructor, the child constructor passes in the name parameter, followed by the definition of its own attribute age. The instance of person is then assigned to the prototype of the child, and then the method Sayage () is defined on the prototype. This way, two different instances of the child have their own properties, including the properties of the reference type, and the same method can be used.
Combinatorial inheritance avoids the pitfalls of prototype chains and constructors, merging them somewhat and becoming the most common inheritance pattern in JavaScript. Furthermore, instanceof and ispropertyof () can also identify objects that are created based on composite inheritance.

Finally, about JS objects and inheritance are still several patterns did not write, or say, I have not yet to go deep research, but, I think, the first combination of the application of the model. And, for why choose the combination mode, know it, know the reason why.

About the JavaScript implementation of the inheritance of several ways (recommended), small series to introduce to everyone here, I hope to help you!

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.