JavaScript 沒有類別(class)這個語法層面的概念,繼承必須靠原型鏈與函式呼叫手動搭建。本文整理幾種常見做法,並比較各自的適用範圍。
var animal=function(name){ //構造函數 this.name=name; this.sayhello=function(){ alert("hi我是"+this.name); }; } animal.prototype.shout=function(){ //prototype主要作用:給類增加一個新的屬性或函數 alert(this.name+"正在叫!"); }; animal.prototype.game=function(){ alert(this.name+"正在玩耍!"); }; var dog=new animal("小黑"); //實例化 dog.sayhello(); dog.shout(); dog.game();
這裡有兩種掛方法的方式:寫在構造函式內的 sayhello 屬於每個實例各自一份;掛在 prototype 上的 shout 與 game 則由所有實例共享。
animal 是父類(超類),誰被繼承誰就是父類。核心動作只有一行:把子類的 prototype 指向父類的實例。
var animal=function(name){ this.name=name; this.sayhello=function(){ alert("hi我是"+this.name); }; } animal.prototype.shout=function(){ alert(this.name+"正在叫!"); }; animal.prototype.game=function(){ alert(this.name+"正在玩耍!"); }; var Dog=function(name){ this.name=name; this.shout=function(){ //重寫父類的函數 alert(this.name+"汪汪叫!"); } } Dog.prototype=Cat.prototype=new animal(); var dog=new Dog("小黑"); dog.sayhello(); dog.shout(); dog.game(); var cat=new Cat("小白"); cat.sayhello(); cat.shout(); cat.game();
Dog 自己定義了 shout,於是先在自己的原型上找到它,父類版本自然被覆蓋;而 sayhello 與 game 則沿原型鏈向上找到。
改進寫法:把繼承動作抽成一個通用函式,避免每個子類都重寫一遍。
var animal=function(name){ this.name=name; this.sayhello=function(){ alert("hi我是"+this.name); }; } Function.prototype.extends=function(superclass){ //extends是保留關鍵字,不能拿出來單獨使用,如var extends=function(){},而這裡可以使用是因為他做為函數的屬性添加上去 this.prototype=new superclass(); }; animal.prototype.shout=function(){ alert(this.name+"正在叫!"); }; animal.prototype.game=function(){ alert(this.name+"正在玩耍!"); }; var Dog=function(name){ this.name=name; this.shout=function(){ alert(this.name+"汪汪叫!"); } } Dog.extends(animal); var dog=new Dog("小黑"); dog.sayhello(); dog.shout(); dog.game(); var dog=new Dog("小白"); dog.sayhello(); dog.shout(); dog.game();
順帶一提,extends 是保留字,不能單獨當變數名宣告,但作為函式屬性名稱是合法的,所以這裡寫成 Function.prototype.extends 沒問題。
var animal=function(name){ this.name=name; this.sayhello=function(){ alert("hi我是"+this.name); }; } animal.prototype.shout=function(){ alert(this.name+"正在叫!"); }; animal.prototype.game=function(){ alert(this.name+"正在玩耍!"); }; var Dog=function(name){ animal.call(this,name); } var dog=new Dog("小黑"); dog.sayhello(); dog.shout(); dog.game();
執行結果:
輸出:hi我是小黑
TypeError: dog.shout is not a function
原因很直接:call(或 apply)只改變了 this 的指向,讓父類構造函式在子類實例上跑一遍,但掛在 prototype 上的方法完全不會被複製過來。
總結:call / apply 適合那些本來就沒有 prototype 的類,或者你確實不需要繼承原型上屬性的場景——它做的是方法替換,而不是屬性與函式的複製。原型繼承則能把原型鏈上的所有成員一併承接過來。
另外要留意一點:透過原型鏈繼承而來的屬性,只有在子類自身沒有同名屬性時才會被讀到;也就是說要「屏蔽」繼承值,得在子類上重新定義,而不是去刪除父類的屬性。
希望本文所述對你的 JavaScript 開發有所幫助。