Home  >  Article  >  Web Front-end  >  What are the ways to implement inheritance in javascript

What are the ways to implement inheritance in javascript

青灯夜游
青灯夜游Original
2021-06-22 16:21:109574browse

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