ES5 继承和 ES 6继承

 ES 5的继承方式:

    //定义父级函数
    function Teacher(){
      this.name = 'yanglong';
    }
    //定义父级函数的原型
    Teacher.prototype.getName = function (){
      return this.name;
    }

    //定义子代函数
    function TeacherChild(){
      Teacher.call(this)  //使得TeacherChild继承Teacher,call用来改变this指针的指向
      this.bug = "bug bug bug";
    };
    //将子代的函数的原型指向父级的函数new出来的对象,这样子代函数的原型链中就可以获得父级原型的方法
    TeacherChild.prototype = new Teacher(); 
    TeacherChild.prototype.getbug = function(){//子代也可以自己定义方法,甚至重写从父级原型获得方法
      Teacher.call(this)
      return this.bug;
    }
    var Teachertest = new Teacher();
    var TeacherChildtest = new TeacherChild();
    console.log(Teachertest)  
    console.log(TeacherChildtest) 

看看打印结果:

 

ES 6的继承方式:

class Teacher { //通过class定义的类,遍历原型是不可以遍历的
      constructor (){
        this.name = "Docter.Yang";
      }
      getName(){
        return this.name
      }
    };

    var Teachertest = new Teacher();
    console.log(typeof Teacher)
    console.log(Teacher.prototype.constructor === Teacher); //true说明原型上的constructor就是类


    class Teacherchild extends Teacher{
      constructor(...args){
        super(...args);
        this.bug = "bug bug bug";
      }
      getName() { //重写了父级的原型方法,我我这里不是获取名字,直接返回bug属性的值
          return this.bug
      }
    }

    var Teachertest = new Teacher();
    var Teacherchildtest = new Teacherchild();

    console.log(Teachertest);
    console.log(Teacherchildtest);
    console.log(Teacherchildtest.getName());

看看打印结果:

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值