js繼承

  • 定義實例的方法主要有兩種:this.XXX = function(){} 和 function.prototype.XXX= function(){}
  • 都至關於類的實例方法,只有new後才能使用,那有什麼區別呢?
  • 假如這兩種方式定義的是同名函數,那麼優先執行this定義的函數
  • 但做爲實例函數,若是定義在構造函數內部,每次實例化都要執行,顯然在浪費內存,也不合理
  • 若是要直接訪問私有字段,應該使用特權方法
  • 相反,若是不須要直接訪問私有字段,應該使用prototype定義的方法,並且應該定義在構造函數外部。

原型鏈繼承的特色
將父類的實例做爲子類的原型
缺點:ide

  • 來自原型對象的引用屬性是全部實例共享的
  • 建立子類實例時,沒法向父類構造函數傳參

其餘:

函數

  • 構造繼承:使用父類的構造函數來加強子類實例 =複製父類的實例屬性給子類
  • Animal.call(this);

缺點:性能

  • 沒法實現函數複用,每一個子類都有父類實例函數的副本,影響性能


組合起來

優勢:this

  • 既是子類的實例,也是父類的實例
  • 可傳參
  • 函數可複用
// Animal(構造函數)
    function Animal(info){
        if(!info){return;}
        this.init(info);
    };
    Animal.prototype={
        constructor:Animal,
        init:function(info){
            this.name = info.name;
        },
        sleep:function(){
            console.log(this.name+" is sleeping ");
        }
    }
    // Cat
    function Cat (){
         Animal.call(this);
         this.name =(name)?name:'tom';
         // this.sleep = function(){
         //     console.log(this.name+" is sleeping111111111 ");
         // }
    };
    // 將父類的實例做爲子類的原型

   var info ={name:'Animal'};
   Cat.prototype = new Animal(info); //實例化1次
  
   // test code

   var cat = new Cat();//實例化2次
   // cat.name;
   console.log(cat.name);
   cat.sleep();
   console.log(cat instanceof Animal); // true
   console.log(cat instanceof Cat); //true

 據說比較完美的作法spa

 

// Animal(構造函數)
    function Animal(info){
        var info = (info)?info:{name:'Animal'};
        this.init(info);
    };
    Animal.prototype={
        constructor:Animal,
        init:function(info){
            this.name = info.name;
        },
        sleep:function(){
            console.log(this.name+" is sleeping ");
        }
    }
    // Cat
    function Cat (){
         Animal.call(this);
         // this.name =(name)?name:'tom';
         // this.sleep = function(){
         //     console.log(this.name+" is sleeping111111111 ");
         // }
    };
    // 只執行一次
   (function(){
       // 建立一個沒有實例方法的類
       var Super = function(){};
       Super.prototype = Animal.prototype;
       Cat.prototype = new Super();

   })();
  
   // test code
   var cat = new Cat();//實例化2次
   // cat.name;
   console.log(cat.name);
   cat.sleep();
   console.log(cat instanceof Animal); // true
   console.log(cat instanceof Cat); //true
View Code
相關文章
相關標籤/搜索