在多數語言中繼承都很重要。JavaScript是一個基於原型的語言,這意味着對象可以直接從其他對象繼承。以下列出幾種常見的js繼承方式。
- 原型鏈繼承
function Father(){ this.status = true; } Father.prototype.getSuper = function(){ return this.status; }; function Son(){ this.substatus = false; } //繼承了 SuperType Son.prototype = new Father(); Son.prototype.getSub = function (){ return this.substatus; }; var instance = new Son(); alert(instance.getSuper()); //true
- 借用構造函數繼承
function Father(){ this.colors = [1,2,3]; } function Son(){ //繼承了 Father Father.call(this); } var instance1 = new Son(); instance1.colors.push(4); alert(instance1.colors); //"1,2,3,4" var instance2 = new Son(); alert(instance2.colors); //"1,2,3"
- 組合繼承
function Father(name){ this.name = name; } Father.prototype.sayName = function(){ alert(this.name); }; function Son(name, age){ //繼承屬性 SuperType.call(this, name); this.age = age; } Son.prototype = new Father(); //將子類的原型指向父類 Son.prototype.constructor = Son; //將子類的constructor指向自己 Son.prototype.sayAge = function(){ alert(this.age); }; var instance = new Son("lh", 19); instance1.sayName(); //"lh"; instance1.sayAge(); //19
- 原型式繼承
function object(o){ function F(){} F.prototype = o; return new F(); } var person = { name: "lh", loves: ["a", "b", "c"] }; var anotherPerson = object(person); anotherPerson.name = "Greg"; anotherPerson.friends.push("d"); alert(person.loves); //"a,b,c,d"
這里的object方法和Object.create()方法類似。
- 寄生式繼承
function object(o){ function F(){} F.prototype = o; return new F(); } function createAnother(obj){ var clone = object(obj); //通過調用函數創建一個新對象 clone.say = function(){ //給這個對象添加方法 alert("hi"); }; return clone; //返回這個對象 } var person = { name: "lh", loves: ["a", "b", "c"] }; var anotherPerson = createAnother(person); anotherPerson.say(); //"hi"
- 寄生組合式繼承
function inheritPrototype(son, father){ var prototype = Object.create(father.prototype); son.prototype = prototype;
prototype.constructor = son; } function Father(name){ this.name = name; } Father.prototype.sayName = function(){ alert(this.name); }; function Son(name, age){ Father.call(this, name); this.age = age; } inheritPrototype(Son, Father); - 使用es6實現
class Father{ constructor(x, y) { this.x = x; this.y = y; } } class son extends Father{ constructor(x, y, age) { super(x, y); // 調用父類的constructor(x, y) this.age= age; } toString() { return this.color + ' ' + super.toString(); // 調用父類的toString() } }
子類繼承父類中constructor中必須先調用super()方法才能訪問this,否則會報錯。