今天我們將講解JavaScript的Constructor prototype inheritance(構造函式的原型繼承),解釋其優點以及如何作用
首先先看以下例子
在Human裡頭,有著Eat(), Drink(), Sleep()等methods
而在Male以及Son則分別多了Husband()以及Study()
假如在定義Male()和Son()時,分別繼承Human的Prototype再分別增加Husband()以及Study()
這樣是否方便許多?
Constructor A繼承另一個Constructor B的prototype物件
兩項設定完成繼承
function Person(name, age){
this.name = name;
this.age = age;
}
Person.prototype.sayHi = function(){
console.log(this.name + '說您好');
};
function Student(name, age, major, grade){
this.major = major;
this.grade = grade;
Person.call(this, name, age);
}
Student.prototype = Object.create(Person.prototype)
let jeremy = new Student('Jeremy Hung', 27, "Engineering", 3.7);
jeremy.sayHi() // Jeremy Hung說您好