在 JavaScript 中,繼承通常用來讓子類別取得父類別的屬性與方法。最常見的兩種方式是:原型繼承與借用構造函數繼承。
原型繼承的核心概念是讓子類別的原型指向父類別的實例,這樣子類別就能透過原型鏈取得父類別的方法與屬性。
function Body(name, age) {
this.name = name;
this.age = age;
}
Body.prototype.sayName = function() {
console.log(this.name);
};
function Another() {}
Another.prototype = new Body("www");
Another.prototype.sex = "male";
Another.prototype.saySex = function() {
console.log(this.sex);
};
var a = new Body("wutao", 10);
var b = new Another();
a.sayName(); // wutao
b.sayName(); // www
b.saySex(); // male
借用構造函數繼承是透過 call 或 apply,在子類別構造函式中呼叫父類別構造函式,讓父類別的屬性與方法被複製到子類別實例中。
function Person(name) {
this.name = name;
this.sayHello = function() {
console.log(this.name);
};
}
function Son(name, age) {
Person.call(this, name);
this.age = age;
this.sayFunc = function() {
console.log(this.name + "-" + this.age);
};
}
var a = new Person("wutao");
var b = new Son("wwwwww", 22);
a.sayHello(); // wutao
b.sayHello(); // wwwwww
b.sayFunc(); // wwwwww-22
function Person(name) {
this.name = name;
this.sayHello = function() {
console.log(this.name);
};
}
function Son(name, age) {
Person.apply(this, [name, age]);
this.age = age;
this.sayFunc = function() {
console.log(this.name + "-" + this.age);
};
}
var b = new Son("ttt", 222);
b.sayHello(); // ttt
b.sayFunc(); // ttt-222
理解這兩種繼承方式,是掌握 JavaScript 物件導向設計的重要基礎。