原型鏈繼承的特色
將父類的實例做爲子類的原型
缺點:ide
其餘:
函數
缺點:性能
組合起來
優勢: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