prototype 是 Function 物件的一個屬性,它指向另一個物件;掛在這個物件上的所有屬性與方法,都會被該建構函式的實例所繼承。同時 prototype 上還有個 constructor 指回建構函式本身,於是形成一個循環參照的原型鏈結構。
理解這件事最大的好處是:那些「所有實例都一樣」的屬性與方法,可以直接定義在 prototype 上,不必在每次 new 的時候重複產生,能省下可觀的記憶體。
function Cat(name, color) { this.name = name; this.color = color; } Cat.prototype.type = 'mammal'; Cat.prototype.eat = function() { console.log('eat fish'); }; var cat1 = new Cat('Kitty', 'white'); var cat2 = new Cat('Smokey', 'black'); console.log(cat1.type); // mammal console.log(cat1.eta === cat2.eta); // TRUE, same reference console.log(cat1.constructor === Cat) // TRUE, from Person.prototype
這段範例把規則示範得很清楚:name 與 color 每隻貓各自擁有,而 type 與 eat 則由原型共享——兩隻貓的 eat 是同一個函式參照,因此相等。
要注意的是範例最後兩行把 eat 誤寫成 eta,實際執行時兩邊都是 undefined 才會相等,這會讓你想驗證的「同一個參照」變成假陽性,記得改回 cat1.eat === cat2.eat。另外,若原型上放的是陣列或物件這類參考型別,所有實例會共用同一份,一邊改動全體受影響,這是原型模式最經典的坑,這類屬性應該寫在建構函式裡。ES6 的 class 語法本質上就是原型繼承的語法糖。希望本文對你的 JavaScript 開發有所幫助。