原型(prototype)是 JavaScript 獨有的概念,透過原型,JavaScript 得以實作繼承機制。JavaScript 本身是基於原型的,每個物件都有一個 prototype 屬性,而 Object 物件的 prototype 屬性則為 null。
以原型實作繼承的範例:
function Person(name){ this.name = name; this.getName = function(){ return this.name; } } function Artist(type){ this.type = type; this.getType = function(){ return this.type; } } Artist.prototype = new Person("arthinking"); var artist = new Artist("Guitar"); alert(artist.getType()); //本身就有 type 屬性 alert(artist.getName()); //從 Person 原型鏈上繼承而來
透過將 Artist 的原型指向 Person 的實例,Artist 產生的物件就能沿著原型鏈取得 Person 的屬性與方法。
JavaScript 中的 this 與傳統物件導向語言有些不同。在傳統語言裡,this 於類別中宣告,代表物件本身;而在 JavaScript 中,this 代表「當前的上下文」,也就是呼叫者的參考。換句話說,this 指向哪個物件,並非由函式宣告時決定,而是由「如何被呼叫」來決定。
var test1 = { name : "test1" } var test2 = { name : "test2" } function getName(){ return this.name; //this 由呼叫該函式的上下文決定 } alert(getName.call(test1));
這裡的 call 是 Function 的一個方法,可用來明確指定 this 所指向的物件。透過 call,我們能把 getName 的 this 綁定到 test1 上,因此輸出為 test1。
理解原型與 this 的運作方式,是掌握 JavaScript 物件導向的核心關鍵。