一、原型鏈繼承 在原型鏈繼承方面,JavaScript與java、c#等語言類似,僅允許單父類繼承。prototype繼承的基本方式如下: 代碼如下: function Parent(){} function Child(){} Child.prototype = new Parent();
通過對象Child的prototype屬性指向父對象Parent的實(shí)例,使Child對象實(shí)例能通過原型鏈訪問到父對象構(gòu)造所定義的屬性、方法等。 構(gòu)造通過原型鏈鏈接了父級對象,是否就意味著完成了對象的繼承了呢?答案是否定的。如: 代碼如下: function Parent(){} function Child(){} Child.prototype = new Parent(); var child = new Child(); alert(child.constructor);//function Parent(){} alert(child instanceof Child);//true
盡管child依然可以作為Child的實(shí)例使用,但此時(shí)已經(jīng)丟失了實(shí)例child原有的對象構(gòu)造信息。彌補(bǔ)該缺陷的方法如下: 代碼如下: function Parent(){} function Child(){} Child.prototype = new Parent(); Child.prototype.constructor = Child; var child = new Child(); alert(child.constructor);//function Parent(){} alert(child instanceof Child);//true
三、對象實(shí)例間的繼承 JavaScript對象的多態(tài)性,允許實(shí)例動態(tài)地添加屬性、方法。該特性造就了JavaScript中的另一種繼承手法——對象實(shí)例間的繼承。如: 代碼如下: var Person = {name:"nathena",age:"26"}; var nathena = {sex:"male"}; (function inlineExtends(so,po)