The old story about JavaScript class inheritance _ Basics

Source: Internet
Author: User

In fact, the first to learn JS when you have seen the implementation of inheritance. It was just to try to understand the code snippet from the book. Today, I think again, it feels like a result of the evolution of a thought exploration.

Inheritance, that is, reuse.

If you put aside the inherent thought of inheritance, let B reuse the members of a, the simplest outrageous approach, b=a;

So, here's the problem: Any changes to B are changes to a (the same object).

Well, copy it, and if the light copy is not safe, use a deep copy.

Problem: The code is reused, but the memory is wasted (whether it's a variable or a method, it's an object in JS).

Do not copy, read or write, you can use the prototype JS, b.__proto__ = A. Generally we do not directly change __proto__, too violent, JS provides a method can be more "moderate" to achieve the purpose--object.create (b).

This method is feasible, but this is only the reuse model of specific objects, if you do "use the object created by Constructorb can reuse the Constructora object prototype"?

The answer is: treat B as constructorb.prototype, and a as constructora.prototype.

Problem:

Workaround:

Declare Constructorb, the system will automatically let Constructorb.prototype.constructor=constructorb; In the above code in order to reuse Constructora.prototype, lost constructor, can be mended.

This is the most basic inheritance, about how subclasses can more commonly invoke constructors and members of the parent class (such as This._super), how to implement inheritance patterns more commonly (such as A=inheritfrom (B)), and so on, not in the scope of this article ^o^

The above is small series for everyone to bring the cliché about the class of JavaScript to inherit all the content, I hope that we support cloud Habitat Community ~

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.