Inheritance of JavaScript objects

Source: Internet
Author: User
Tags object constructor inheritance return

1. Object posing as
Object impersonation is to execute the constructor of the parent class by using this of the subclass in the subclass to impersonate the parent class. This obtains the properties and methods of the parent class, but this way only inherits the properties and methods defined in the parent class constructor, and any properties and methods on the stereotype are not visible to the child classes:
Using object impersonation to implement inheritance
function Supertype ()
{
This.prop = ["prop"];

This.method = function () {return ' method ';};
}
SuperType.prototype.protoProp = "Proto";

Function subtype ()
{
Temporary methods
This.inherit = supertype;
Impersonate inheritance
This.inherit ();
Delete Temporary method
Delete This.inherit;
}

var sub = new subtype ();
alert (Sub.prop); property, inheriting the parent class attribute
Alert (Sub.method ()); Method, inheriting the parent class methods
alert (Sub.protoprop); Undefined, cannot inherit the properties of the parent class prototype

2. Prototype Chain inheritance
Using a prototype chain makes it easy to inherit the properties and methods of the parent class, but if the property of the parent class is a reference type, there may be problems with the interaction of multiple instances of the parent class or subclass, that is, an instance that has changed the property may be visible to another instance.
Prototype chain inheritance
function Supertype ()
{
This.prop = ["prop"];

This.method = function () {return ' method ';};
}
SuperType.prototype.protoProp = "Proto";

Function subtype ()
{
}
Using a prototype chain to inherit
Subtype.prototype = new Supertype ();

var sub = new subtype ();

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.