JavaScript中原型链例子
《摘自Object-Oriented JavaScript, 3rd Edition》
function Shape(){
this.name = 'Shape';
this.toString = function(){
return this.name;
}
}
function TwoDShape(){
this.name = '2D shape';
}
function Triangle(side, height){
this.name = 'Triange';
this.side = side;
this.height = height;
this.getArea = function(){
return this.side * this.height /2;
}
}
TwoDShape.prototype = new Shape();
Triangle.prototype = new TwoDShape();
//对象的原型链修改后,需要重新将原型的constructor指向原来的对象
TwoDShape.prototype.constructor = TwoDShape;
Triangle.prototype.constructor = Triangle;
As you know from the previous chapter, overwriting the prototype (as opposed to just adding properties to it), has side effects on the constructor property. Therefore, it’s a good idea to reset the constructor property after inheriting
重写或者覆盖原型之后(这里不是说添加方法到原型上),对constructor
这个属性有负影响。因此,在继承之后需要重置constructor
属性