Home  >  Article  >  Web Front-end  >  About inheritance of JavaScript classes (recommended)

About inheritance of JavaScript classes (recommended)

怪我咯
怪我咯Original
2017-03-31 09:37:391195browse

In fact, when I first started learning JS, I saw the implementation of inheritance. At that time, I was just trying to understand the code snippets from the book. I thought about it again today, and I feel that this is the result of the evolution of thinking.

Inheritance, that is, reuse.

If you put aside the inherent idea of ​​inheritance and let b reuse the members of a, the simplest and crudest way is, b=a;

Then, here comes the problem: any changes to b, It is a change to a (the same object).

Okay, then make a copy. If the shallow copy is not safe enough, use a deep copy.

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

Without copying, only reading and not writing, you can use the JS prototype, b.proto = a. Generally, we do not change the proto directly, as it is too violent. JS provides a method that can achieve the goal in a relatively "gentle" way - Object.create(b).

About inheritance of JavaScript classes (recommended)

This method is feasible, but it is only the reuse mode of specific objects. What if "the object created by ConstructorB can reuse the prototype of the object of ConstructorA"?

The answer is: treat b as ConstructorB.prototype and a as ConstructorA.prototype.

About inheritance of JavaScript classes (recommended)

Question:

About inheritance of JavaScript classes (recommended)

Solution:

When declaring ConstructorB, the system will automatically let ConstructorB.prototype.constructor=ConstructorB; In order to reuse ConstructorA.prototype in the above code , if the constructor is lost, just add it.

About inheritance of JavaScript classes (recommended)

The above is the most basic inheritance. Regarding how subclasses can call the constructor and members (such as this._super) of the parent class more generally, How to implement the inheritance pattern more generally (such as A=inheritFrom(B)), etc., is beyond the scope of this article^O^

The above is the detailed content of About inheritance of JavaScript classes (recommended). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn