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

What is the mode of inheritance in JavaScript

2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge of what is the way of inheritance in JavaScript, the content is detailed and easy to understand, the operation is simple and fast, and it has a certain reference value. I believe you will gain something after reading this article on inheritance in JavaScript. Let's take a look.

Prototype chain

First of all, you have to understand what the prototype chain is. It is described in great detail in an article about the relationship and difference between proto and prototype.

The basic idea of prototype chain inheritance is to point one prototype object to an instance of another type.

Function SuperType () {this.property = true} SuperType.prototype.getSuperValue = function () {return this.property} function SubType () {this.subproperty = false} SubType.prototype = new SuperType () SubType.prototype.getSubValue = function () {return this.subproperty} var instance = new SubType () console.log (instance.getSuperValue () / / true

The code defines two types, SuperType and SubType, each with a property and a method. SubType inherits SuperType, and inheritance is achieved by creating an instance of SuperType and assigning that instance to SubType.prototype.

The essence of the implementation is to rewrite the prototype object and replace it with an instance of a new type, so all the properties and methods that exist in the instance of SuperType now exist in SubType.prototype.

We know that when you create an instance, there is an internal pointer in the instance object that points to the prototype that created it and associates it. In this case, the code SubType.prototype = new SuperType () also creates an internal pointer in SubType.prototype to associate SubType.prototype with SuperType.

So instance points to the prototype of SubType, and the prototype of SubType points to the prototype of SuperType, and then when instance calls the getSuperValue () method, it goes all the way up the chain.

Add method

When adding a method to the SubType prototype, if there is the same name on the parent class, SubType will override the method to achieve the re-purpose. But this method still exists in the parent class.

Remember that you can't add it literally, because, as mentioned above, inheriting through instances is essentially rewriting, and then using literal forms, it's a rewrite again, but this rewriting has nothing to do with the parent class, so it causes the prototype chain to be truncated.

Function SuperType () {this.property = true} SuperType.prototype.getSuperValue = function () {return this.property} function SubType () {this.subproperty = false} SubType.prototype = new SuperType () SubType.prototype = {getSubValue:function () {return this.subproperty}} var instance = new SubType () console.log (instance.getSuperValue () / / error

problem

Simply using prototype chain inheritance, the main problem comes from prototypes that contain reference type values.

Function SuperType () {this.colors = ['red',' blue', 'green']} function SubType () {} SubType.prototype = new SuperType () var instance1 = new SubType () var instance2 = new SubType () instance1.colors.push (' black') console.log (instance1.colors) / / ["red", "blue", "green", "black"] console.log (instance2.colors) / / ["red", "blue" "green", "black"]

A colors attribute is defined in the SuperType constructor. When SubType is inherited through the prototype chain, this property will appear in SubType.prototype, just like creating SubType.prototype.colors, so it will cause all instances of SubType to share this attribute, so instance1 modifying the reference type value of colors will also be reflected in instance2.

Borrow constructor

This method is designed to solve the problem caused by the inclusion of reference type values in the prototype.

The idea of this method is to call the parent class constructor inside the subclass constructor, and the apply () and call () methods can be used to change the execution context of the object.

Function SuperType () {this.colors = ['red',' blue', 'green']} function SubType () {/ / inherit SuperType SuperType.call (this)} var instance1 = new SubType () var instance2 = new SubType () instance1.colors.push (' black') console.log (instance1.colors) / / ["red", "blue", "green", "black"] console.log (instance2.colors) / / ["red" "blue", "green"]

The SuperType constructor is called when the new SubType instance is created, so that all the object initialization code defined in the SuperType function is executed on the new SubType object.

As a result, each instance of SubType will have its own copy of the colors property.

Transfer parameters

Another advantage with the help of constructors is that parameters can be passed.

Function SuperType (name) {this.name = name} function SubType () {/ / inherit SuperType SuperType.call (this, 'Jiang') this.job =' student'} var instance = new SubType () console.log (instance.name) / / Jiang console.log (instance.job) / / student

problem

If only with the help of the constructor, the methods are all defined in the constructor, so the function cannot be reused.

Combinatorial inheritance (prototype chain + constructor)

Combinatorial inheritance is a pattern that combines prototype chain inheritance with constructors to give full play to the advantages of both.

The idea is to use the prototype chain to inherit the prototype properties and methods, and to inherit the instance properties by borrowing the constructor.

In this way, function reuse is realized by defining methods on the prototype, and each instance can be guaranteed to have its own properties.

Function SuperType (name) {this.name = name this.colors = ['red',' blue', 'green']} SuperType.prototype.sayName = function () {console.log (this.name)} function SubType (name, job) {/ / inherit attribute SuperType.call (this) Name) this.job = job} / / inheritance method SubType.prototype = new SuperType () SubType.prototype.constructor = SuperType SubType.prototype.sayJob = function () {console.log (this.job)} var instance1 = new SubType ('Jiang',' student') instance1.colors.push ('black') console.log (instance1.colors) / / ["red", "blue", "green" "black"] instance1.sayName () / / 'Jiang' instance1.sayJob () / /' student' var instance2 = new SubType ('Jacks,' doctor') console.log (instance2.colors) / ["red", "blue", "green"] instance2.sayName () / /'J' instance2.sayJob () / / 'doctor'

This pattern avoids the defects of prototype chain and constructor inheritance, combines their advantages, and is the most commonly used inheritance mode.

Prototype inheritance

Prototypes allow you to create new objects based on existing objects without having to create custom types.

Function object (o) {function F () {} F.prototype = o return new F ()}

Inside the object function, create a temporary constructor, then use the incoming object as the prototype of the constructor, and * return a new instance of this temporary type.

In essence, object performs a shallow copy of the objects passed in.

Var person = {name: 'Jiang', friends: [' Shelby', 'Court']} var anotherPerson = object (person) console.log (anotherPerson.friends) / / [' Shelby', 'Court']

For this mode to go, you must have one object as the basis for another.

In this example, person, as the basis for another object, passes person into object, and the function returns a new object.

This new object uses person as a prototype, so its prototype contains a primitive type and a reference type.

So it means that if there is another object associated with the person,anotherPerson modification array friends, it will also be reflected in this object.

Object.create () method

ES5 standardizes prototype inheritance through the Object.create () method, which accepts two parameters, one is the object used as the prototype of the new object and an optional object that defines additional properties for the new object, the behavior is the same, and the basic usage is the same as the above object, except that object cannot accept the second parameter.

Var person = {name: 'Jiang', friends: [' Shelby', 'Court']} var anotherPerson = Object.create (person) console.log (anotherPerson.friends) / / [' Shelby', 'Court']

Parasitic inheritance

The idea of parasitic inheritance is similar to parasitic constructors and factory patterns, that is, to create a function that encapsulates the inheritance process only.

Function createAnother (o) {var clone = Object.create (o) / create a new object clone.sayHi = function () {/ / add method console.log ('hi')} return clone / / return this object} var person = {name:' Jiang'} var anotherPeson = createAnother (person) anotherPeson.sayHi ()

A new object anotherPeson is returned based on person. The new object not only has the properties and methods of person, but also has its own sayHi method.

This is a useful pattern when you focus on objects rather than custom types and constructors.

Parasitic combinatorial inheritance

In the combination pattern mentioned earlier (prototype chain + constructor), the parent constructor needs to be called twice when inheriting.

Parent class

Function SuperType (name) {this.name = name this.colors = ['red',' blue', 'green']}

* times in the subclass constructor

Function SubType (name, job) {/ / inherit attribute SuperType.call (this, name) this.job = job}

Point the prototype of the subclass to the instance of the parent class for the second time

/ / inheritance method SubType.prototype = new SuperType ()

When var instance = new SubType () is used, two sets of name and color properties are generated, one on the SubType instance and one on the SubType prototype, but the instance masks the prototype's.

This problem can be avoided by using parasitic combination mode.

This pattern inherits the property by borrowing the constructor and the method through the mixed form of the prototype chain.

Basic idea: you don't have to call the constructor of the parent class to specify the prototype of the subtype, all we need is a copy of the prototype of the parent class.

In essence, parasitic inheritance is used to inherit the prototype of the parent class, assigning the result to the prototype of the child type.

Function inheritPrototype (subType, superType) {var prototype = Object.create (superType.prototype) prototype.constructor = subType subType.prototype = prototype}

This function implements the simplest form of parasitic combinatorial inheritance.

This function takes two arguments, a subclass and a parent class.

* step is to create a copy of the parent prototype. The second step is to add the constructor attribute to the created copy, and the third part points the prototype of the subclass to this copy.

Function SuperType (name) {this.name = name this.colors = ['red',' blue', 'green']} SuperType.prototype.sayName = function () {console.log (this.name)} function SubType (name, job) {/ / inheritance attribute SuperType.call (this, name) this.job = job} / / inheritance inheritPrototype (SubType, SuperType) var instance = new SubType (' Jiang' 'student') instance.sayName ()

Add: to use Object.create directly is to take apart the functions encapsulated above, so that the demonstration can be understood more easily.

Function SuperType (name) {this.name = name this.colors = ['red',' blue', 'green']} SuperType.prototype.sayName = function () {console.log (this.name)} function SubType (name, job) {/ / inherit attribute SuperType.call (this) Name) this.job = job} / / inherit SubType.prototype = Object.create (SuperType.prototype) / / repair constructor SubType.prototype.constructor = SubType var instance = new SubType ('Jiang',' student') instance.sayName ()

ES6 adds a new method, Object.setPrototypeOf, to create associations directly without manually adding the constructor attribute.

/ / inherit Object.setPrototypeOf (SubType.prototype, SuperType.prototype) console.log (SubType.prototype.constructor = SubType) / / true this is the end of the article on "what is the way of inheritance in JavaScript?" Thank you for reading! I believe that everyone has a certain understanding of the knowledge of "what is the way of inheritance in JavaScript". If you want to learn more knowledge, you are welcome to follow the industry information channel.

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

Internet Technology

Wechat

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

12
Report