所有的 JavaScript 內建物件都擁有一個唯讀的 prototype 屬性。

可以為原型添加『屬性』和『方法』,但是無法為該內建物件指派不同的原型,不過卻可以為使用者定義的物件指派新原型。

prototype

例如,若要將『方法』加入至 Array 物件 (此方法會傳回最大陣列元素的值)

請宣告函式,並將它加入至 Array.prototype,然後使用它。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function array_max( ){
var i, max = this[0];
for (i = 1; i < this.length; i++)
{
if (max < this[i])
max = this[i];
}
return max;
}
Array.prototype.max = array_max;
var myArray = new Array(7, 1, 3, 11, 25, 9);
console.log(myArray.max());
// Output: 25

繼承方法

當繼承函式執行時,this 值指向繼承的物件,而不是在函式內擁有屬性的原型物件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var o = {
a: 2,
m: function() {
return this.a + 1;
}
};
console.log(o.m()); // 3
// 在這裡呼叫 o.m 時「this」指的是 o
var p = Object.create(o);
// p 是個從 o 繼承的物件
p.a = 4; // 在 p 建立屬性「a」
console.log(p.m()); // 5
// 呼叫 p.m is 時「this」指的是 p
// 因此在 p 繼承 o 的函式 m 時,
// 「this.a」指的是 p.a:也就是 p 的自有屬性「a」

參考