JavaScript inheritance Detailed

Source: Internet
Author: User

Common inheritance is divided into two kinds, an interface inheritance, an inheritance method signature, an implementation inheritance, and an actual method of inheritance. JS only supports the latter one.

1 prototype chain

First, we look at the relationship between prototypes, constructors, and instances. If we make the prototype object of one function equal to another instance, then another prototype object equals another instance, and so on, it forms the prototype chain.

Code:

function Supertype () {

This.name=true;

}

Supertype.prototype.getvalue=function () {

return this.name;

}

Function subtype () {

this.age=12;

}

Subtype.prototype=new supertype (); Build the prototype chain and let subtype inherit all the properties and methods of Supertype.

var instance=new subtype ();

Alert (Instance.getvalue ());//true

2 borrowing constructors

Use the call () or the Apply () method

function Supertype () {

this.color=["Red", "Blue"];

}

Function subtype () {

Supertype.call (this);

}

var instance1=new subtype ();

Borrowing a constructor does not change the prototype, and each instance has its own copy of the property.

JavaScript inheritance Detailed

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.