13. 使用原型 prototype
真正的重用。
prototype 是一個屬性,將共用的部分設定在此,代表是共用部分。
複寫原型,只要直接指定,不用更改呼叫方式。 在原型加入、改變了屬性、方法,所有該原型的物件也立刻會變動,除非有被複寫。
hasOwnProperty
若屬性定義在物件實例,物件的 hasOwnProperty 方法會回傳 true。
原型鍊
讓一個原型繼承另一個原型: e.g. ShowDog 原型繼承自 Dog 原型
- 建立一 Dog 建構式
- 設 Dog 建構式的原型屬性
- 建立一 ShowDog 建構式
- 將 ShowDog 建構式的原型,設定成 Dog 的實例 new Dog()
- 為 ShowDog 原型設 constructor 屬性:ShowDog.prototype.constructor = ShowDog;
- 增修 ShowDog 建構式的原型
- 建立 ShowDog 實例
constructor
instenceof 所有你所繼承的建構式都會是 true
obj.constructor 物件.建構式,沒有從新設置也會繼承上一個原型。
.call
// ShowDog 建構式
function ShowDog (name, color, age, master){
    this.name = name,
    this.color = color,
    this.age = age,
    this.master = master
}
// 用 Dog 建構式來設定
function ShowDog (name, color, age, master){
    Dog.call( this, name, color, age) 
    // 這裡的 this 是 ShowDog
    // 叫用 Dog 建構式,將 this 帶入 Dog 替換主體,傳入引數、執行 Dog 建構式
    // 在 Dog 建構式中,將以 ShowDog 的實例為 this,
    // Dog 建構式會幫 ShowDog 建立出 name, color, age。
    this.master = master
}
Object 就是一個原型
利用繼承複寫內建行為
Robot.prototype.toString = function(){
    return (this.name + ' 屬於 ' this.owner);
}
- toString
- toLocalString 可以針對國家地區提供本地化字串
- valueOf 提供使用該方法的物件
要小心,Object 中不可復寫的屬性
- constructor
- hasOwnProperty
- isPrototypeOf
- propertyIsEnumerable 是否可透過迭代來存取此屬性。