继承:es5 vs es6

es5如何实现继承

es5实现继承主要是通过原型来实现的

  1. 首先实现一个父类
      function Father(name, age){
        this.name = name;
        this.age = age;
        this.work = function (){
            console.log('Father is working!')
        }
    }
    
    Father.prototype.address = 'chengdu';
    
    Father.prototype.code = function() {
        console.log('Father is coding!')
    }
    
  2. 其次实现一个子类继承父类
    function Child(name, age) {
        Father.call(this, name, age);
    }
    
    Child.prototype = Father.prototype;
    

这里面主要是两个部分:

1.父类原型数据的继承

Child.proptotype = Father.proptotype

2.父类非原型部分的数据的继承

Father.call(this, name, age)

这种继承方式叫做混合继承

现在查看一个继承类父类的子类是什么样的:

image

es6如何实现继承

通过extends就可以实现

class Father {
    constructor(name, age){
        this.name = name;
        this.age = age;
    }
    work(){
        console.log('father is working');
    }
}

class Child extends Father{
    constructor(name, age) {
        super(name, age);
    }
}

这样子类就拥有了父类的属性和方法了

你可能感兴趣的:(继承:es5 vs es6)