今天我們將講解JavaScript的Prototype inheritance(原型繼承),解釋其作用方式
首先,在JavaScript中物件會有__proto__屬性(隱藏屬性),而此屬性指向了該物件的原型(prototype)
若物件A的__proto__儲存物件B,則物件A會繼承物件B的所有Attributes & Methods
舉例:物件A(tim),物件B(jeremy)
let jeremy = {
name: "Jeremy",
sayHi() {
console.log("你好");
},
};
let tim = {
__proto__: jeremy,
};
console.log(tim.name); //Jeremy
console.log(tim.sayHi()); //你好
由上例可以看出,物件B(tim)藉由設定__proto__為jeremy,繼承了所有jeremy物件的屬性和方法
其次,所有從constructor function製造出來的物件,其__proto__屬性都是指向constructor function的prototype
function Car(brand, year) {
this.brand = brand;
this.year = year;
this.init = function () {
console.log(this.brand + " engine start");
};
}
//透過Car constructor function建立兩個function(ford, toyota)
let ford = new Car("ford", 10);
let toyota = new Car("toyota", 15);
console.log(ford.__proto__ == Car.prototype); //true
因此,如果要在ford和toyota新增attribute或method,可以在constructor function prototype進行新增即可
//新增stop function
Car.prototype.stop = function () {
console.log(this.brand + "停止了");
};
//toyota也能使用,新增method
toyota.stop(); // toyota停止了