父級:
function Parent(name){ this.name=name; } Parent.prototype.sayHello=function(){ console.log("Hello,"+this.name); }
#原型鏈繼承
function Kid(){}; Kid.prototype=new Parent("who"); var k=new Kid(); console.log(k.name); //who console.log(k.sayHello()); //Hello,who
弊端:建立實例時無法向父級傳參詞
建構繼承
function Kid(name){ Parent.call(this,name); }; var k=new Kid("who"); console.log(k.name); //who console.log(k.sayHello()); //error
弊端:無法取得父級原型鏈屬性
實例繼承
function Kid(name){ var p=new Parent(name); return p; }; var k=new Kid("who"); console.log(k.name); //who console.log(k.sayHello()); //Hello,who
弊端:實例是父級的實例
拷貝繼承
function Kid(name){ var p=new Parent(name); for(var item in p){ Kid.prototype[item]=p[item]; } } var k=new Kid("who"); console.log(k.name); //who console.log(k.sayHello()); //Hello,who
弊端:太佔用記憶體
組合繼承
function Kid(name){ Parent.call(this,name); } Kid.prototype=new Parent(); var k=new Kid("who"); console.log(k.name); //who console.log(k.sayHello()); //Hello,who
弊端:呼叫了兩次父類別建構函數
寄生組合繼承
function Kid(name){ Parent.call(this,name); } (function(){ var p=function(){}; p.prototype=Parent.prototype; Kid.prototype=new p(); })()
弊端:寫法比較繁瑣
以上是原型繼承的幾種方式介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!