How to implement parasitic composable inheritance using JavaScript
This article mainly introduces JavaScript parasitic combined inheritance, and analyzes the principles, implementation methods and related precautions of parasitic combined inheritance in detail in the form of examples. Friends in need can refer to the following
The examples in this article describe JavaScript parasitic composable inheritance. I share it with you for your reference. The details are as follows:
In fact, the book "JavaScript Advanced Programming" already has the complete code. As long as you understand the code, you will know what this inheritance is about.
First of all, in js, there are two ways to define attributes for objects:
//通过执行构造函数设置属性 function A(){ this.a = 1; } //通过原型设置属性 A.prototype.b = 1;
So:
If a class Sub wants to inherit another class Super, it needs to inherit the parent class Attributes under the prototype, you also need to execute the constructor of the parent class.
That is, If a class Sub wants to inherit another class Super, it must not only realize the inheritance of prototype properties and methods through the prototype chain, but also realize the inheritance by calling the parent class constructor in the subclass constructor. Inheritance of instance properties.
1. Inherit the attributes under the prototype
As you can see above, the attributes under the prototype of the Super class are not inherited, so this part needs to be inherited below. .
Direct "=" will definitely not work, because after modifying the properties in Sub.prototype, it cannot affect the objects in Super.prototype, that is, it cannot Sub.prototype=Super.prototype
.
First write a method to create a copy of the object
function object(o){ function A(){} A.prototype = o var ox = new A() return ox }
The object ox obtained by the above function has all the properties of the object o (on the prototype chain), and modifying the properties of ox does not It will affect o, which is equivalent to making a copy of o.
Prototypal inheritance is the "object" function above, which can be found in many class library source codes
Simply speaking, prototypal inheritance means that there is no need to instantiate the parent class. Directly instantiating a temporary copy implements the same prototype chain inheritance. (That is, the prototype of the subclass points to the instance of the copy of the parent class to achieve prototype sharing)
tips: As we all know, prototype chain inheritance is achieved by pointing the prototype of the subclass to the instance of the parent class. Prototype sharing, and prototypal inheritance is that the prototype of the subclass points to an instance of the copy of the parent class to achieve prototype sharing.
ECMAScirpt 5 standardizes prototypal inheritance through the new Object.create()
method.
Using the object method, you can "copy" the properties of Super.prototype to Sub.prototype. Of course, you also need to correct the pointing of the constructor here.
function inherit(subType,superType){ var prototype=Object.create(superType.prototype); prototype.constructor=subType; subType.prototype=prototype; }
2. Execute the constructors of the parent class and the subclass respectively, and inherit the attributes under this part:
//父类 function Super(){ this.sss=1 } //子类 function Sub(){ //arguments是Sub收到的参数,将这个参数传给Super Super.apply(this, arguments) } //实例 sub = new Sub()
Super.apply(this, arguments )
This sentence executes the Super class as an ordinary function, but the this of the Super class is replaced by this of the Sub class, and the parameters received by Sub are also passed to Super
The final execution result Equivalent to sub.sss=1
Attached are the characteristics, advantages and disadvantages of various inheritance methods
There was a time when JavaScript was not standardized regarding class implementation inheritance, resulting in There are various codes that implement inheritance; in fact, no matter how the code changes, inheritance is based on two methods:
1. Through the prototype chain, that is, the prototype of the subclass points to the parent class instances to achieve prototype sharing.
2. Borrow the constructor, that is, through js's apply and call, the subclass can call the attributes and methods of the parent class;
The prototype chain method can realize all attribute methods Sharing, but properties and methods cannot be exclusive (for example, Sub1 modifies the function of the parent class, and all other subclasses Sub2, Sub3... cannot call the old function);
And Borrowing constructors In addition to exclusive properties and methods, parameters can also be passed in subclass constructors, but the code cannot be reused. Generally speaking, can realize the exclusive use of all attribute methods, but cannot achieve the sharing of attributes and methods. (For example, if Sub1 adds a new function, and then wants to use it in Sub2, Sub3... It is impossible to implement, only Sub2, Sub3... can be added in the constructor respectively).
Combined inheritance is to use the above two inheritance methods together. Shared properties and methods are implemented using prototype chain inheritance, and exclusive properties and methods are implemented using borrowed constructors. Therefore, combined inheritance almost perfectly implements js inheritance; why is it said "almost"? Because geeks who are serious about it discovered that there is a small bug in combinatorial inheritance. When implementing it, the super class (parent class) was called twice. Is it possible that the performance is not up to standard? How to solve it? So "parasitic inheritance" came out.
Parasitic inheritance (prototypal inheritance) means that there is no need to instantiate the parent class. Instead, a temporary copy is directly instantiated to achieve the same prototype chain inheritance. (That is, the prototype of the subclass points to the instance of the copy of the parent class to achieve prototype sharing)
"Parasite combination inheritance" uses "parasitic inheritance" to fix the small bug of "combination inheritance", thus making js Perfect implementation is inherited.
Example code:
function SuperType(name,colors){ this.name=name; this.colors=colors; } SuperType.prototype.getSuperProperty=function(){ return this.name; } function SubType(job,name,colors){ SuperType.call(this,name,colors); this.job=job; } SubType.prototype.getSubPrototype=function(){ return this.job; } function inherit(subType,superType){ var prototype=Object.create(superType.prototype); prototype.constructor=subType; subType.prototype=prototype; } inherit(SubType,SuperType); var instance=new SubType("doctor","John",["red","green"]); console.log(instance.getSubPrototype()); //输出"doctor" console.log(instance.getSuperProperty()); //输出"John",成功调用在父类原型定义的方法
The attribute inheritance code isSuperType.call(this,name,colors);
The prototype inheritance code is inherit(SubType,SuperType);
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
related articles:
How to implement collision detection in JS
How to use it with gulp and bower in angular1?
What are the methods for debugging js scripts?
How to implement a search box using Angular
Detailed introduction to interpolation in vue
The above is the detailed content of How to implement parasitic composable inheritance using JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



In function inheritance, use "base class pointer" and "derived class pointer" to understand the inheritance mechanism: when the base class pointer points to the derived class object, upward transformation is performed and only the base class members are accessed. When a derived class pointer points to a base class object, a downward cast is performed (unsafe) and must be used with caution.

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Inheritance error debugging tips: Ensure correct inheritance relationships. Use the debugger to step through the code and examine variable values. Make sure to use the virtual modifier correctly. Examine the inheritance diamond problem caused by hidden inheritance. Check for unimplemented pure virtual functions in abstract classes.

Inheritance and polymorphism affect the coupling of classes: Inheritance increases coupling because the derived class depends on the base class. Polymorphism reduces coupling because objects can respond to messages in a consistent manner through virtual functions and base class pointers. Best practices include using inheritance sparingly, defining public interfaces, avoiding adding data members to base classes, and decoupling classes through dependency injection. A practical example showing how to use polymorphism and dependency injection to reduce coupling in a bank account application.

Detailed explanation of C++ function inheritance: Master the relationship between "is-a" and "has-a" What is function inheritance? Function inheritance is a technique in C++ that associates methods defined in a derived class with methods defined in a base class. It allows derived classes to access and override methods of the base class, thereby extending the functionality of the base class. "is-a" and "has-a" relationships In function inheritance, the "is-a" relationship means that the derived class is a subtype of the base class, that is, the derived class "inherits" the characteristics and behavior of the base class. The "has-a" relationship means that the derived class contains a reference or pointer to the base class object, that is, the derived class "owns" the base class object. SyntaxThe following is the syntax for how to implement function inheritance: classDerivedClass:pu

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

What is object-oriented programming? Object-oriented programming (OOP) is a programming paradigm that abstracts real-world entities into classes and uses objects to represent these entities. Classes define the properties and behavior of objects, and objects instantiate classes. The main advantage of OOP is that it makes code easier to understand, maintain and reuse. Basic Concepts of OOP The main concepts of OOP include classes, objects, properties and methods. A class is the blueprint of an object, which defines its properties and behavior. An object is an instance of a class and has all the properties and behaviors of the class. Properties are characteristics of an object that can store data. Methods are functions of an object that can operate on the object's data. Advantages of OOP The main advantages of OOP include: Reusability: OOP can make the code more

C++ function inheritance should not be used in the following situations: When a derived class requires a different implementation, a new function with a different implementation should be created. When a derived class does not require a function, it should be declared as an empty class or use private, unimplemented base class member functions to disable function inheritance. When functions do not require inheritance, other mechanisms (such as templates) should be used to achieve code reuse.
