Several ways to realize the inheritance of JS

Source: Internet
Author: User

Turn from: The Magic of the Sky Mans blog

Objective

As an object-oriented weakly typed language, the inheritance is also one of the most powerful features of JS. So how to implement inheritance in JS? Let's wait and see.

How to implement JS inheritance

Since we want to implement inheritance, first we have to 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: prototype An instance of a parent class as a child class

function Cat(){ }Cat.prototype = new Animal();Cat.prototype.name = ‘cat‘;// Test Codevar 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

Characteristics:

    1. A very purely inherited relationship, an instance of a subclass, and an instance of the parent class.
    2. The parent class adds a new prototype method/prototype property that the subclass can access to
    3. Simple and easy to implement

Disadvantages:

    1. To add properties and methods to a subclass, you must new Animal() execute after such a statement and not put it in the constructor
    2. Unable to implement multiple inheritance
    3. The reference property from the prototype object is shared by all instances (see Appendix Code for details: Example 1)
    4. Cannot pass parameter to parent class when creating child class instance

Recommended index: ★ (3, 42 major fatal defects)

2. Construction Inheritance

Core: Use the constructor of the parent class to enhance the subclass instance, which is equivalent to copying the instance property of the parent class to the subclass (useless to the prototype)

function Cat(name){  Animal.call(this);  this.name = name || ‘Tom‘;}// Test Codevar cat = new Cat();console.log(cat.name);console.log(cat.sleep());console.log(cat instanceof Animal); // falseconsole.log(cat instanceof Cat); // true

Characteristics:

    1. Resolves an issue where subclass instances share parent class reference properties in 1
    2. When you create a child class instance, you can pass parameters to the parent class
    3. Multiple inheritance can be implemented (call multiple parent objects)

Disadvantages:

    1. The instance is not an instance of the parent class, just an instance of the child class
    2. Only instance properties and methods of the parent class can be inherited and cannot inherit the prototype properties/methods
    3. Function reuse is not possible, each subclass has a copy of the parent class instance function, which affects performance

Recommended index: ★ (Disadvantage 3)

3. Instance Inheritance

Core: adds a new attribute to the parent class instance, returning as a subclass instance

function Cat(name){  var instance = new Animal();  instance.name = name || ‘Tom‘;  return instance;}// Test Codevar cat = new Cat();console.log(cat.name);console.log(cat.sleep());console.log(cat instanceof Animal); // trueconsole.log(cat instanceof Cat); // false

Characteristics:

    1. Does not restrict the invocation, whether it is new 子类() or 子类() , the returned object has the same effect

Disadvantages:

    1. Instance is an instance of the parent class, not an instance of the child class
    2. Multiple inheritance is not supported

Recommended Index: ★

4. Copy Inheritance
function Cat(name){  var animal = new Animal();  for(var p in animal){    Cat.prototype[p] = animal[p];  }  Cat.prototype.name = name || ‘Tom‘;}// Test Codevar cat = new Cat();console.log(cat.name);console.log(cat.sleep());console.log(cat instanceof Animal); // falseconsole.log(cat instanceof Cat); // true

Characteristics:

    1. Support Multiple inheritance

Disadvantages:

    1. Low efficiency and high memory consumption (because you want to copy the properties of the parent class)
    2. Unable to get parent class non-enumerable method (non-enumerable method, cannot be accessed using for in)

Recommended index: ★ (disadvantage 1)

5. Combination Inheritance

Core: by calling the parent class construct, inheriting the property of the parent class and preserving the advantages of the pass parameter, and then implementing the function reuse by using the parent class instance as the subclass prototype

function Cat(name){  Animal.call(this);  this.name = name || ‘Tom‘;}Cat.prototype = new Animal();// Test Codevar cat = new Cat();console.log(cat.name);console.log(cat.sleep());console.log(cat instanceof Animal); // trueconsole.log(cat instanceof Cat); // true

Characteristics:

    1. compensate for the defect in mode 2, can inherit instance properties/methods, or inherit prototype properties/Methods
    2. is both an instance of a subclass and an instance of the parent class
    3. There is no reference attribute sharing issue
    4. Can be passed the parameter
    5. Functions can be reused

Disadvantages:

    1. A two-time parent constructor was called, and two instances were generated (the subclass instance masked the sub-class prototype)

Recommendation index: ★★★★ (consumes only a bit more memory)

6. Parasitic combination inheritance

Core: by parasitic way, the instance property of the parent class is cut off, so that when two times the construction of the parent class is called, the two instance method/property is not initialized, the disadvantage of avoiding the combination inheritance

function Cat(name){  Animal.call(this);  this.name = name || ‘Tom‘;}(function(){  // 创建一个没有实例方法的类  var Super = function(){};  Super.prototype = Animal.prototype;  //将实例作为子类的原型  Cat.prototype = new Super();})();// Test Codevar cat = new Cat();console.log(cat.name);console.log(cat.sleep());console.log(cat instanceof Animal); // trueconsole.log(cat instanceof Cat); //true

Characteristics:

    1. Perfect

Disadvantages:

    1. Achieve more complex

Recommendation index: ★★★★ (achieve complexity, deduct a star)

Appendix Code:

Example one:

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‘]原因分析:关键点:属性查找过程执行tom.features.push,首先找tom对象的实例属性(找不到),那么去原型对象中找,也就是Animal的实例。发现有,那么就直接在这个对象的features属性中插入值。在console.log(kissy.features); 的时候。同上,kissy实例上没有,那么去原型上找。刚好原型上有,就直接返回,但是注意,这个原型对象中features属性值已经变化了。

JS implementation of several methods of inheritance (GO)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.