標籤:call article 缺點 head return 原型 混合繼承 組合 也有
js的物件導向是基於原型的,因此js的對象繼承方式也有些特殊,下面我具體談一下js的幾種常用繼承方式
1.使用new方法繼承
實現原理:在子類的建構函式中調用父類的建構函式。
function Parent(name){ this.name = name; this.age = 40; this.sayName = function(){ console.log(this.name); } this.sayAge = function(){ console.log(this.age); }}function Child(name){ this.parent = Parent; this.parent(name); delete this.parent; this.saySomething = function(){ console.log(this.name); this.sayAge(); }}var child = new Child(‘Lee‘);child.saySomething();//Lee//40
2.使用call方法實現
實現原理:使用call方法改變函數上下文this指向,使之傳入具體的函數對象。
function Parent(name){ this.name = name; this.age = 40; this.say = function(){ console.log(this.name + this.age); }}function Child(name){ Parent.call(this,name); }var child = new Child(‘Mike‘);child.say();//Mike40
3.使用apply方法實現
實現原理:使用apply方法改變函數上下文this指向,使之傳入具體的函數對象。
function Parent(name){ this.name = name; this.age = 40; this.say = function(){ console.log(this.name + this.age); }}function Child(name){ Parent.apply(this,[name]); //Parent.apply(this,arguments); 效果同上}var child = new Child(‘Wade‘);child.say();//wade40
4.使用原型鏈(prototype)方法實現
實現原理:子類的原型對象指向父類的執行個體,即重寫類的原型。
function Parent(name){ this.name = name; this.say = function(){ console.log(this.name +‘ ‘+ this.age); }}function Child(age){ this.age = age; this.saySomething = function(){ console.log(this.name); }}Child.prototype = new Parent(‘petter‘);var child = new Child(20);child.say();//petter 20
5.使用混合方式實現
實現原理:使用原型鏈實現對原型屬性和方法的繼承,而通過借用建構函式來實現對執行個體屬性的繼承。
function Parent(age){ this.name = ‘petter‘; this.age = age;}Parent.prototype.say = function(){ return this.name + ‘ ‘ + this.age;}function Child(age){ Parent.call(this,age); //Parent.apply(this,[age]); this.age = age;}Child.prototype = new Parent();var child = new Child(21);child.say();//petter 21
6. 寄生組合繼承
實現原理:通過寄生方式,砍掉父類的執行個體屬性,這樣,在調用兩次父類的構造的時候,就不會初始化兩次執行個體方法/屬性,避免的混合繼承的缺點
function Animal(name){ this.name = name; this.sleep = function(){ console.log(this.name + ‘is sleeping‘); }}function Cat(name){ Animal.call(this); this.name = name || ‘Tom‘;}(function(){ // 建立一個沒有執行個體方法的類 var Super = function(){}; Super.prototype = Animal.prototype; //將執行個體作為子類的原型 Cat.prototype = new Super();})();// Test Codevar cat = new Cat();console.log(cat.name);//Tomconsole.log(cat.sleep());//Tom is sleepingconsole.log(cat instanceof Animal); // trueconsole.log(cat instanceof Cat); //true
js繼承的實現方式