继承: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);
    }
}

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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容