1. 程式人生 > >ES5 繼承和 ES 6繼承

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());

看看列印結果: