Implementing inheritance by borrowing constructors

Source: Internet
Author: User

Calling a super-type constructor inside a subtype constructor
Remember, a function is simply an object that executes code in a particular environment, so you can also execute a constructor on a newly created object by using call () and apply ()

function Supertype () {
this.colors=["Red", "Blue", "green"];
}

Function subtype () {
Inherited the supertype.
Supertype.call (this); //seconded a super-type constructor

}

var instance1=new subtype ();
Instance1.colors.push ("yellow");
Console.log (instance1.colors);

var instance2=new subtype (); ["Red", "Blue", "green", "yellow"]
Console.log (instance2.colors);//["Red", "Blue", "green"]

By using call () or apply (), the Supertype constructor is actually called in the context of the newly created subtype instance, so that it executes on the new subtype object
All object initialization code defined in the Supertype () function. As a result, all instances of subtype will have their own colors properties.














Implementing inheritance by borrowing constructors

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.