A personal understanding of JavaScript prototypes, prototype chains, and inheritance

Source: Internet
Author: User

Inheritance is one of the most-talked-about concepts in oo language, and it is also a difficult concept for beginners who touch JavaScript first. There are two main types of inheritance: One is interface inheritance, the other is implementation inheritance. In ECMAScript, we only support implementation of inheritance, so let's talk about implementing inheritance today. Implementation of inheritance is to inherit the actual method, mainly rely on the prototype chain to achieve. In this case, we need to discuss what a prototype chain is.

1. What is a prototype

To understand the prototype chain we first need to know what a prototype is. We know that each function has a prototype property, which is a pointer to an object that contains the properties and methods shared by all instances. So I personally think it can be so simple to understand: The prototype is the prototype attribute.

While the prototype property has its own prototype object, and Pototype object certainly has its own constuct attribute, construct attribute has its own Constuctor object, the magic thing to happen, This last constructor object is the function itself that we construct!

2, about prototype and _proto_

(1). Each object has a property named __proto__;

(2). Each constructor (the constructor standard starts with uppercase, such as function (), Object (), and so on, the constructor that comes with JS, and what you create) has a method called prototype (note: Since it is a method, So is an object (JS function is also the object), so prototype also with the __proto__ attribute);

(3). The __proto__ property of each object points to the prototype of its own constructor;

So in most cases we can think of this: _proto_===constructor.prototype (except in some cases, such as: Objects created by object.create () do not apply this equation)

3. Prototype chain

Speaking of which, what exactly is a prototype chain? In fact, it is very clear. Since each object has a _proto_ property, and in JavaScript everything is object, it eventually forms a chain connected by the _proto_, and the recursive access eventually ends and the final value is null. Then this chain is the prototype chain.

When the JavaScript engine looks for the properties of an object, it finds out whether the property exists on the object itself, and if it does not exist, it is searched on the prototype chain. (but will not look for its own prototype)

4. Inheritance

First, the prototype chain-type inheritance

There is a basic pattern for implementing the prototype chain inheritance, the code is as follows:

function supertype () {    this.property=ture;}
Supertype.prototype.getsupervalue=function () {
return this.prototype;
};
Function subtype () {
This.subproperty=false;
}
Subtype.prototype=new subtype ();//Inherited Supertype
Subtype.prototype.getsubvalue=function () {
return this.subproperty;
};
var instance=new subtype ();
Alert (Instance.getsupervalue ());//true

Basic prototype chain inheritance is simple but it has two problems: 1. When inheriting through the prototype chain, the prototype will actually become an instance of another type. As a result, the original instance attributes have naturally become the archetypal attributes of the present. 2. When you create an instance of a subtype, you cannot pass a function to a super-type constructor.

Second, borrowing constructor inheritance

The superclass constructor is called inside the subtype constructor, and the constructor can be executed on the newly created object by using the call () and the Apply () methods.

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

The problem with the constructor is that zooming in is in the constructor, so the reuse of the function is impossible. Also, methods defined in a super-type prototype are not visible to the subtypes, and all types can only use the constructor pattern.

Third, the combination of inheritance

function Super () {    //only the basic and reference properties are declared here    this.val = 1;    This.arr = [1];}  The function is declared here SUPER.PROTOTYPE.FUN1 = function () {}; Super.prototype.fun2 = function () {};//super.prototype.fun3...function Sub () {    super.call (this);   Core    //...} Sub.prototype = new Super ();    Core var sub1 = new Sub (1), var sub2 = new Sub (2), alert (sub1.fun = = = Sub2.fun);   True

In order to solve the problem of borrowing constructor inheritance, combinatorial inheritance arises.

Combination inheritance puts the instance functions on the prototype object to implement the function reuse. It also preserves the advantages of borrowing constructors by Super.call (this), inheriting the basic and reference properties of the parent class, and preserving the advantages of the ability to pass arguments, through sub.prototype = new Super (), inheriting the parent function, and implementing the function reuse.

The combination inheritance avoids the disadvantage of the inheritance of the prototype chain and the borrowing of the constructor, and blends their advantages: There is no reference attribute sharing problem, the parameter can be passed, and the function can be reused. As a result, it becomes the most common inheritance pattern in JavaScript.

Cons: The biggest problem with combinatorial integration is that the two-time super-type constructor is called in any situation.

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);//First Call supertype ()    This.age=age}subtype.prototype =new supertype ();//second call to Supertype () subtype.prototype.constructor=function () {    alert (this.age);};

  

Iv. Parasitic combination Inheritance

Since the combination of inheritance also has shortcomings, it is necessary to compensate, so there is a parasitic combination of inheritance.

The basic pattern of parasitic combination inheritance is as follows:

function Inheritprototype (subtype,supertype) {    var prototype=object (supertype.prototype);//Create Object    prototypr.constructor=subtype;//Enhanced object  compensates for default constructor properties lost due to rewrite prototypes
subtype.prototype=prototype;//the specified object assigns the newly created object to the child type's prototype
}

The Inheritprototype () function In this example implements the simplest form of combinatorial inheritance. We can call the Inheritprototype () function area to replace the sub-type prototype assignment function in the previous example:

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);//First Call supertype ()    this.age=age}  Inheritprototype (subtype,supertype); Subtype.prototype.sayage=function () {    alert (this.age);};

The funny body of this example now calls only one supertype constructor, avoiding unnecessary and unnecessary attributes created on Subtype.prototype. At the same time, the prototype chain remains unchanged, so instanceof and isprototypeof () can be used normally. So now parasitic combination inheritance is the most ideal way to inherit.

PS: There is not much to explain about prototype inheritance and parasitic inheritance. You can check the relevant information on their own, not recommended to use (personal views).

A personal understanding of JavaScript prototypes, prototype chains, and inheritance

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.