What are the ways to implement inheritance in javascript
How JavaScript implements inheritance: 1. Prototype chain inheritance; use the instance of the parent class as the prototype of the subclass. 2. Structural inheritance; use the constructor of the parent class to enhance the subclass instance. 3. Instance inheritance; add new features to parent class instances and return them as subclass instances. 4. Copy inheritance. 5. Combination inheritance. 6. Parasitic combination inheritance.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
JS is an object-oriented weakly typed language, and inheritance is also one of its very powerful features. So how to implement inheritance in JS? let us wait and see.
How to implement JS inheritance
Since we want to implement inheritance, we must first have a parent class. The code is as follows:
// 定义一个动物类 function Animal (name) { // 属性 this.name = name || 'Animal'; // 实例方法 this.sleep = function(){ console.log(this.name + '正在睡觉!'); } } // 原型方法 Animal.prototype.eat = function(food) { console.log(this.name + '正在吃:' + food); };
1. Prototype chain inheritance
Core: Use the instance of the parent class as the prototype of the subclass
function Cat(){ } Cat.prototype = new Animal(); Cat.prototype.name = 'cat'; // Test Code var cat = new Cat(); console.log(cat.name); console.log(cat.eat('fish')); console.log(cat.sleep()); console.log(cat instanceof Animal); //true console.log(cat instanceof Cat); //true
Features:
Very pure Inheritance relationship, an instance is an instance of a subclass, and is also an instance of the parent class
The parent class adds a new prototype method/prototype attribute, and the subclass can access it
Simple and easy to implement
Disadvantages:
If you want to add attributes and methods to subclasses, you can use the Cat constructor In the function, add instance attributes to the Cat instance. If you want to add prototype properties and methods, they must be executed after statements like new Animal().
Multiple inheritance cannot be implemented
All properties from the prototype object are shared by all instances
When creating a subclass instance, parameters cannot be passed to the parent class constructor
2. Construction inheritance
Core: Using the constructor of the parent class to enhance the instance of the subclass is equivalent to copying the instance attributes of the parent class to the subclass (no prototype is used)
function Cat(name){ Animal.call(this); this.name = name || 'Tom'; } // Test Code var cat = new Cat(); console.log(cat.name); console.log(cat.sleep()); console.log(cat instanceof Animal); // false console.log(cat instanceof Cat); // true
Features:
Solved the problem in 1 that subclass instances share parent class reference attributes
When creating a subclass instance, you can pass parameters to the parent class
Multiple inheritance can be achieved (call multiple parent class objects)
Disadvantages:
Instances are not instances of the parent class, just subclasses The instance
can only inherit the instance properties and methods of the parent class, but cannot inherit the prototype properties/methods
Function reuse cannot be realized. Subclasses have copies of parent class instance functions, which affects performance
3. Instance inheritance
Core:Add new features to parent class instances , returned as a subclass instance
function Cat(name){ var instance = new Animal(); instance.name = name || 'Tom'; return instance; } // Test Code var cat = new Cat(); console.log(cat.name); console.log(cat.sleep()); console.log(cat instanceof Animal); // true console.log(cat instanceof Cat); // false
Features:
does not limit the calling method, whether it is
new subclass()
orsubclass Class()
, the returned object has the same effect
Disadvantages:
Instances are instances of the parent class, not subclasses The instance
does not support multiple inheritance
4. Copy inheritance
function Cat(name){ var animal = new Animal(); for(var p in animal){ Cat.prototype[p] = animal[p]; } // 如下实现修改了原型对象,会导致单个实例修改name,会影响所有实例的name值 // Cat.prototype.name = name || 'Tom'; 错误的语句,下一句为正确的实现 this.name = name || 'Tom'; } // Test Code var cat = new Cat(); console.log(cat.name); console.log(cat.sleep()); console.log(cat instanceof Animal); // false console.log(cat instanceof Cat); // true
Features:
Support multiple inheritance
Disadvantages:
Low efficiency and high memory usage (because the attributes of the parent class need to be copied)
Unable to obtain non-enumerable methods of the parent class (non-enumerable methods cannot be accessed using for in)
5 , Combined inheritance
Core:By calling the parent class constructor, inherit the properties of the parent class and retain the advantages of passing parameters, and then use the parent class instance as the subclass prototype to achieve Function reuse
function Cat(name){ Animal.call(this); this.name = name || 'Tom'; } Cat.prototype = new Animal(); // 组合继承也是需要修复构造函数指向的。 Cat.prototype.constructor = Cat; // Test Code var cat = new Cat(); console.log(cat.name); console.log(cat.sleep()); console.log(cat instanceof Animal); // true console.log(cat instanceof Cat); // true
Features:
makes up for the shortcomings of method 2. You can inherit instance properties/methods and prototype properties/methods
It is both an instance of the subclass and an instance of the parent class
There is no problem of sharing reference attributes
can be transferred Parameters
Function can be reused
Disadvantages:
The parent class constructor is called twice function, two instances are generated (the subclass instance shields the one on the subclass prototype)
6. Parasitic combination inheritance
Core: Through parasitism, cut off the instance attributes of the parent class, so that when the parent class's constructor is called twice, the instance methods/attributes will not be initialized twice, avoiding the shortcomings of combined inheritance
function Cat(name){ Animal.call(this); this.name = name || 'Tom'; } (function(){ // 创建一个没有实例方法的类 var Super = function(){}; Super.prototype = Animal.prototype; //将实例作为子类的原型 Cat.prototype = new Super(); })(); // Test Code var cat = new Cat(); console.log(cat.name); console.log(cat.sleep()); console.log(cat instanceof Animal); // true console.log(cat instanceof Cat); //true Cat.prototype.constructor = Cat; // 需要修复下构造函数
Features:
Perfect
Disadvantages:
The implementation is more complicated
Appendix code:
Example 1:
function Animal (name) { // 属性 this.name = name || 'Animal'; // 实例方法 this.sleep = function(){ console.log(this.name + '正在睡觉!'); } //实例引用属性 this.features = []; } function Cat(name){ } Cat.prototype = new Animal(); var tom = new Cat('Tom'); var kissy = new Cat('Kissy'); console.log(tom.name); // "Animal" console.log(kissy.name); // "Animal" console.log(tom.features); // [] console.log(kissy.features); // [] tom.name = 'Tom-New Name'; tom.features.push('eat'); //针对父类实例值类型成员的更改,不影响 console.log(tom.name); // "Tom-New Name" console.log(kissy.name); // "Animal" //针对父类实例引用类型成员的更改,会通过影响其他子类实例 console.log(tom.features); // ['eat'] console.log(kissy.features); // ['eat']
Cause analysis:
Key point: attribute search process
To execute tom.features.push, first look for the instance attribute of the tom object (cannot be found),
Then look for it in the prototype object, which is the instance of Animal. If you find that there is, then insert the value directly into the features attribute of this object.
When console.log(kissy.features); Same as above, if it is not available on the kissy instance, then go and find it on the prototype.
If it happens to exist on the prototype, it will be returned directly. However, note that the value of the features attribute in this prototype object has changed.
【Related recommendations: javascript learning tutorial】
The above is the detailed content of What are the ways to implement inheritance in 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.

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

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.

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

Interface: An implementationless contract interface defines a set of method signatures in Java but does not provide any concrete implementation. It acts as a contract that forces classes that implement the interface to implement its specified methods. The methods in the interface are abstract methods and have no method body. Code example: publicinterfaceAnimal{voideat();voidsleep();} Abstract class: Partially implemented blueprint An abstract class is a parent class that provides a partial implementation that can be inherited by its subclasses. Unlike interfaces, abstract classes can contain concrete implementations and abstract methods. Abstract methods are declared with the abstract keyword and must be overridden by subclasses. Code example: publicabstractcla
