最直覺的繼承寫法,就是把父類別的實例直接指定給子類別的 prototype。
function Shape() {
this.name = 'shape';
this.toString = function () {
return this.name;
};
}
function TwoDShape() {
this.name = '2D shape';
}
function Triangle(side, height) {
this.name = 'Triangle';
this.side = side;
this.height = height;
this.getArea = function () {
return this.side * this.height / 2;
};
}
/* inheritance */
TwoDShape.prototype = new Shape();
Triangle.prototype = new TwoDShape();
問題是:一旦把 prototype 整個替換掉,原本指向子類別的 constructor 就一起被沖掉了。所以在設定完繼承關係後,把 constructor 補回來是個好習慣。
TwoDShape.prototype.constructor = TwoDShape; Triangle.prototype.constructor = Triangle;
把方法從構造函式內部搬到 prototype,就不必每 new 一次就重新建立一份函式,記憶體與效能都更好。
function Shape() {}
Shape.prototype.name = 'shape';
Shape.prototype.toString = function () {
return this.name;
};
function TwoDShape() {}
TwoDShape.prototype = new Shape();
TwoDShape.prototype.constructor = TwoDShape;
TwoDShape.prototype.name = '2d shape';
function Triangle(side, height) {
this.side = side;
this.height = height;
}
Triangle.prototype = new TwoDShape();
Triangle.prototype.constructor = Triangle;
Triangle.prototype.name = 'Triangle';
Triangle.prototype.getArea = function () {
return this.side * this.height / 2;
};
既然只需要原型鏈,其實不必真的 new 出父類別實例,直接把 prototype 指向父原型即可,省下一次物件建立。
TwoDShape.prototype = Shape.prototype; TwoDShape.prototype.constructor = TwoDShape; TwoDShape.prototype.name = '2d shape'; Triangle.prototype = TwoDShape.prototype; Triangle.prototype.constructor = Triangle; Triangle.prototype.name = 'Triangle';
但這裡藏著副作用:因為傳的是參照,子類別與父類別指向的是同一個物件。子類別一動原型,父類別立刻跟著被改,Shape 的 name 會莫名其妙變成 'Triangle'。
解法是插入一個空的臨時函式 F,讓原型鏈多一層中繼站——子類別有自己的原型物件可以放東西,同時又能沿鏈查到父類別。
function Shape() {}
Shape.prototype.name = 'shape';
Shape.prototype.toString = function () {
return this.name;
};
function TwoDShape() {}
var F = function () {}
F.prototype = Shape.prototype;
TwoDShape.prototype = new F();
TwoDShape.prototype.constructor = TwoDShape;
TwoDShape.prototype.name = '2d shape';
function Triangle(side, height) {
this.side = side;
this.height = height;
}
F.prototype = TwoDShape.prototype;
Triangle.prototype = new F();
Triangle.prototype.constructor = Triangle;
Triangle.prototype.name = 'Triangle';
Triangle.prototype.getArea = function () {
return this.side * this.height / 2;
};
這個模式兼得兩邊的優點:不必執行父類別的構造函式,也不用複製屬性,而且父子原型彼此獨立。它就是下一篇文章中 extend 封裝函式的核心原理。