Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement inheritance in JS

2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how to inherit JS, and the content of the article is of high quality, so the editor will share it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.

Prototype

Inheritance depends on the prototype, of course, the prototype is not the focus of this article, let's review it.

In fact, the concept of prototype is very simple:

All objects have a property _ _ proto__ that points to an object, that is, a prototype

The prototype of each object can be found through constructor, and the constructor can also be found through prototype.

All functions can find the Function object through _ _ proto__

All objects can find the Object object through _ _ proto__

Objects are connected by _ _ proto__, which is called a prototype chain. Attributes that do not exist on the current object can be found layer by layer through the prototype chain to the top-level Object object

In fact, the most important content of the prototype is these, there is no need to read those lengthy articles about what the prototype is, beginners will be more and more confused.

Of course, if you want to know more about the prototype, you can read the article I wrote earlier.

ES5 implementation inheritance

Generally speaking, there are two ways to inherit ES5 implementation. If you have written about it before, you can copy it directly.

Generally speaking, I think the content of this part is more for the interview at the moment.

Combinatorial inheritance

Combinatorial inheritance is the most common way of inheritance.

Function Parent (value) {this.val = value} Parent.prototype.getValue = function () {console.log (this.val)} function Child (value) {Parent.call (this, value)} Child.prototype = new Parent () const child = new Child (1) child.getValue () / / 1child instanceof Parent / / true

The core of the above inheritance method is to inherit the properties of the parent class through Parent.call (this) in the constructor of the subclass, and then change the prototype of the subclass to new Parent () to inherit the function of the parent class.

The advantage of this inheritance method is that the constructor can pass parameters, it will not share the reference property with the parent class, and the parent class function can be reused, but there is also a disadvantage that the parent class constructor is called when inheriting the parent class function. As a result, there are many unnecessary parent class attributes on the prototype of the subclass, resulting in a waste of memory.

Parasitic combinatorial inheritance

This inheritance method optimizes combinatorial inheritance, and the disadvantage of combinatorial inheritance is that the constructor is called when inheriting the parent class function, and we just need to optimize this.

Function Parent (value) {this.val = value} Parent.prototype.getValue = function () {console.log (this.val)} function Child (value) {Parent.call (this, value)} Child.prototype = Object.create (Parent.prototype, {constructor: {value: Child, enumerable: false, writable: true, configurable: true}) const child = new Child (1) child.getValue () / / 1child instanceof Parent / / true

The core of the above inheritance implementation is to assign the prototype of the parent class to the subclass and set the constructor as the subclass, which not only solves the problem of useless parent class attributes, but also correctly finds the constructor of the subclass.

How Babel compiles ES6 Class

Why did we say in the previous article that ES5 implementation inheritance is more for interview, because we can now directly use class to implement inheritance.

But class is something of ES6 after all, and in order to be more compatible with browsers, we usually compile ES6 code through Babel. Next, let's take a look at what the compiled code looks like through Babel.

Function _ possibleConstructorReturn (self, call) {/ /. Return call & (typeof call = 'object' | | typeof call = =' function')? Call: self;} function _ inherits (subClass, superClass) {/ /. SubClass.prototype = Object.create (superClass & & superClass.prototype, {constructor: {value: subClass, enumerable: false, writable: true, configurable: true}}); if (superClass) Object.setPrototypeOf? Object.setPrototypeOf (subClass, superClass): subClass.__proto__ = superClass;} var Parent = function Parent () {/ / verify whether it is this _ classCallCheck (this, Parent) constructed by Parent;}; var Child = (function (_ Parent) {_ inherits (Child, _ Parent); function Child () {_ classCallCheck (this, Child); return _ possibleConstructorReturn (this, (Child.__proto__ | Object.getPrototypeOf (Child)) .apply (this, arguments)) } return Child;} (Parent))

The above code is part of the compiled code, hiding some non-core code, let's first read the _ inherits function.

The code for setting up the subclass prototype is actually exactly the same as the parasitic combination inheritance, and the side also shows that this implementation is the best. But this part of the code added a sentence Object.setPrototypeOf (subClass, superClass), in fact, the purpose of this code is to inherit the static methods of the parent class, the previous two inheritance methods we have implemented do not have this function.

Then the code for the Child constructor is basically similar to the previous implementation. So generally speaking, the way Babel implements inheritance is parasitic composite inheritance, which is nothing more than a static method of inheriting the parent class.

Problems in inheritance

Having talked about how to implement inheritance, let's consider whether inheritance is a good choice.

Generally speaking, I personally don't like inheritance very much, and the reasons are one by one.

Let's look at the code first. If we now want to describe several different brands of cars, cars must be a parent category, and then each brand of cars are a subcategory.

Class Car {constructor (brand) {this.brand = brand} wheel () {return'4 wheels'} drvie () {return 'car can drive'} addOil () {return 'car can refuel'} Class OtherCar extends Car {}

This part of the code looks fine at the moment, realizing several basic functions of the car, and we can also extend all kinds of cars through subclasses.

But now there are new energy vehicles, new energy vehicles do not need to be refueled. Of course, in addition to refueling this function is not required, the basic functions of several other cars are still needed.

If the new energy car directly inherits the parent car, there will be the first problem, the gorilla and the banana problem. This problem means that we only need a banana now, but we get the gorilla holding the banana. We don't need the gorilla, but the parent is forced to give it to the offspring. Inheritance can override the methods of the parent class, but you can't choose what you want to inherit.

In addition, it is difficult for a single parent class to describe all the scenarios, so we may need to add several different parent classes to describe more scenarios. As it continues to expand, there is bound to be duplication of code, which is one of the problems with inheritance.

In addition to the above two problems, inheritance is also strongly coupled, and the class is coupled to its parent class anyway.

Now that there is strong coupling, the architecture must be fragile. Once there is something wrong with the design of our parent class, it will have a great impact on maintenance. Because all the subclasses are coupled to the parent class, changing anything in the parent class may result in the need to change all the subclasses.

How to solve the problem of inheritance

Inheritance is more about describing what a thing is, and if it is not described well, there will be all kinds of problems, so do we have a way to solve these problems? The answer is a combination.

What is a combination? You can think of this concept as, you have all kinds of parts, you can use these parts to create all kinds of products, and the combination is more to describe what a thing can do.

Now let's put the case of the previous car into a combination.

Function wheel () {return "four wheels";} function drvie () {return "car can drive";} function addOil () {return "car can be refueled"; / / tanker const car = compose (wheel, drvie, addOil) / / New Energy vehicle const energyCar = compose (wheel, drive)

From the pseudo code above, you must also find that combination is better than inheritance. Whatever you want to describe, you can do it by combining several functions. The code is clean and easy to reuse.

On how to inherit JS to share here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report