Inheritance of JavaScript objects

Source: Internet
Author: User
Tags 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

Cloud Intelligence Leading the Digital Future

Alibaba Cloud ACtivate Online Conference, Nov. 20th & 21st, 2019 (UTC+08)

Register Now >

Starter Package

SSD Cloud server and data transfer for only $2.50 a month

Get Started >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.