The inheritance of JavaScript

Source: Internet
Author: User

Implementation of prototype inheritance

1 Simplified version

function Superclass () {...} function Subclass () {...} Subclass.prototype=new superclass ();

Subclass.prototype.constructor=subclass;

Note: This method is correct in most cases, but sometimes the problem occurs. If function superclass (name) {this.name=name.touppercase ()}, an error occurs when calling new superclass ().

2 Comparison of a generic implementation of a prototype inheritance

//The child of the function does not inherit the custom property of parent
functionInherite (child,parent) {varf=function(){}; //F share a prototype with parentF.prototype=Parent.prototype; //Child 's prototype is an instance of FChild.prototype=NewF (); Child.prototype.constructor=Child ;}functionSuperclass (name) { This. name=name;}functionSubclass (Name,age) {Superclass.call ( This, name); This. age=Age ;} Inherate (subclass,superclass);

Benefit: Avoid creating an instance of a parent class (superclass), and avoid side effects of some parent constructors

3 Clean prototype inheritance

function superclass () {} function Subclass () {}subclass.prototype=object.create (superclass.prototype);

Subclass.prototype.constructor=subclass;

Note: the Object.create () method is supported only by some browsers

The inheritance of JavaScript

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.