search
HomeWeb Front-endJS TutorialWhat 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.

What are the ways to implement inheritance in javascript

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() or subclass 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!

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
JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment