原型链继承的特色
将父类的实例做为子类的原型
缺点: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