"JavaScript" Class Inheritance (object impersonation) and prototype inheritance __ deep understanding of prototypes and prototype chains

Source: Internet
Author: User

There are many types and implementations of inheritance in JavaScript in many books, basically two kinds: class inheritance (object impersonation) and prototype inheritance.

Class inheritance (Object impersonation): The method of defining its own properties inside a function, when the subclass inherits, using call or apply to implement the object impersonation, the type definition of things are copied, so that the inheritance subclass and the parent class is not much association, does not affect each other, it is beneficial to protect some of their own private properties.

Prototype inheritance: Each function has its own prototype (prototype) property, which is created automatically when the instance object is generated. It is also an object, with properties and methods that can be shared between instances. The properties and methods of the instance itself are included in the constructor. In other words, the properties and methods inside the constructor, after being instantiated, become local properties and methods, and the properties and methods in the prototype (prototype) are only a reference in the instance and can therefore be shared by multiple instances.

Both have advantages and disadvantages, and practical applications are mostly mixed applications.

Here's an example of mixing the two to understand:

function A (x) { This. x =x; } a.prototype.a="a"; function B (x, y) { This. y =y; A.call ( This, x);//class Inheritance} b.prototype.b1=function () {alert ("B1"); } B.prototype=NewA ();//prototype InheritanceB.PROTOTYPE.B2 =function () {alert ("B2"); } b.prototype.constructor=B; varobj =NewB1,3);

"JavaScript" Class Inheritance (object impersonation) and prototype inheritance __ deep understanding of prototypes and prototype chains

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.