Implement javascript inheritance

1. ES6 extends

Use extends keyword to achieve inheritance between classes. This is much more convenient than using inheritance in ES5.

//定义类父类
class Animal {
    
       
  constructor(color) {
    
       
    this.color = color;   
  }   
  greet(sound) {
    
       
    console.log(sound);   
  }  
}   
class Dog extends Animal {
    
       
  constructor(color) {
    
       
    super(color);   
    this.color = color;   
  }  
}   

let dog = new Dog('黑色');  
dog.greet('汪汪');  // "汪汪"
console.log(dog.color); // "黑色"


2. Use prototype and call

   const extend = (Target, Origin) => {
    
    
           // Origin.call(Target)
            function Fun() {
    
     }
            Fun.prototype = Origin.prototype
            Target.prototype = new Fun()
            //Target.prototype = Object.create(Origin.prototype)
            Target.prototype.constructor = Target
            Target.prototype.uber = Origin.prototype
        }
        Father.prototype.b = 1
        function Father() {
    
    
            this.a=2
        }

        function Son() {
    
    
            // Father.call(this)
        }
        extend(Son, Father)
        var son = new Son();
        var father = new Father();
        console.log(son.b)
        console.log(son.a)

3. Parasitic combined inheritance

function Animal(color) {
    
    
  this.color = color;
  this.name = 'animal';
  this.type = ['pig', 'cat'];
}
Animal.prototype.greet = function(sound) {
    
    
  console.log(sound);
}
function Dog(color) {
    
    
  Animal.apply(this, arguments);
  this.name = 'dog';
}
/* 注意下面两行 */

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.getName = function() {
    
    
  console.log(this.name);
}
var dog = new Dog('白色');   
var dog2 = new Dog('黑色');     
dog.type.push('dog');   
console.log(dog.color);   // "白色"
console.log(dog.type);   // ["pig", "cat", "dog"]
console.log(dog2.type);  // ["pig", "cat"]
console.log(dog2.color);  // "黑色"
dog.greet('汪汪');  //  "汪汪"


The function of a shallow copy of Object.create() is as follows:

function create(obj) {
    
    
  function F() {
    
    };
  F.prototype = obj;
  return new F();
}

One more thing to note here, because the Animal prototype is copied and assigned to Dog.prototype, the constructor property on Dog.prototype has also been rewritten, so we have to fix this problem:Dog.prototype.constructor = Dog;

Use closures to privatize variables

const inherit = (() => {
    
    
    let F = function () {
    
    }
    return (Target,Origin) => {
    
    
        F.prototype= Origin.prototype
        Target.prototype = new F()
        Target.prototype.constructor = Target
        Target.prototype.uber = Origin.prototype
    }
})()

Comprehensive analysis of inheritance

Guess you like

Origin blog.csdn.net/pz1021/article/details/105150115