JavaScript 的物件透過原型 (Prototype) 機制相互繼承功能。
物件建構式
在建立Object時被呼叫,透過物件的建構函式定義屬性、方法,來建立物件實例。
- 宣告一個類別 (class)。
- this 定義屬性。
- prototype 定義方法。
- new 添加物件實例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| function Dog(name, color, weight) { this.name = name; this.color = color; this.weight = weight; } Dog.prototype.bark = function(){ console.log(this.name + '汪汪!'); } let Fido = new Dog('Fido','棕色',12);
Fido.bark(); // Fido汪汪! console.log(Fido); // Dog {name: "Fido", color: "棕色", weight: 12}
Fido.size = "中型犬"; // 添加新屬性 delete Fido.size; // 刪除屬性
Fido.game = function(){ // 添加新方法 console.log(this.name + '來玩你丟我撿'); }
|
原型繼承
一個類別 (class)可繼承其他類別的屬性和方法,然後再延伸增加自己的屬性和方法。
- .prototype.constructor 屬性,指向物件的建構函式。
- .prototype._proto__ 屬性,指向物件繼承的原型。
- Object.create(目標物件原型[,屬性]) 方法,使用目標物件作為新創建物件的原型來創建新物件。
- Object.getPrototypeOf(obj) 方法,取得該物件的原型。
- instanceof 運算子,判斷物件是否建立自指定的建構函式。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| function Animal(family) { this.kingdom = '動物界'; this.family = family; } Animal.prototype.move = function() { console.log(this.name + '奔跑'); }
function Dog(name, color, weight) { Animal.call(this, '犬科'); this.name = name; this.color = color; this.weight = weight; }
Dog.prototype = Object.create(Animal.prototype); //建立多層繼承,透過Object.create複製了Animal.prototype全部的屬性
Dog.prototype.constructor = Dog; //需要再將constructor重新指定回物件的建構函式本身。
Dog.prototype.bark = function(){ console.log(this.name + '汪汪!'); }
let Fido = new Dog('Fido','棕色',12);
Fido.bark(); // Fido汪汪! Fido.move(); // Fido奔跑
console.log(Fido); // Dog {kingdom: "動物界", family: "犬科", name: "Fido", color: "棕色", weight: 12}
console.log(Object.getPrototypeOf(Fido)); // Animal {constructor: ƒ, bark: ƒ}
console.log(Fido instanceof Animal); // true
|