function Shape(){};
Shape.prototype.name = "shape";
Shape.prototype.toString = function(){return this.name;};
function TwoDShape(){};
TwoDShape.prototype = Shape.prototype; //TwoDShape.prototype原型继承Shape.prototype;原型
TwoDShape.prototype.constructor = TwoDShape; //constructor属性进行重置
TwoDShape.prototype.name = "2D shape";
function Triangle(side,height){
this.side = side;
this.height = height;
}
Triangle.prototype = TwoDShape.prototype; //Triangle.prototype原型继承TwoDShape.prototype;原型
Triangle.prototype.constructor = Triangle; //constructor属性进行重置
Triangle.prototype.name = "Triangle";
Triangle.prototype.getArea = function(){return this.side*this.height};
var my = new Triangle(5,10);
my.getArea();
my.name;
这样简单的拷贝原型从效率上来说固然会好一些,但是也有副作用,由于采用的都是按引用传递,子对象和父对象指向的是同一个对象,
所以一旦子对象原型进行了修改,父对象也会随只改变.
Triangle.prototype.name = "Triangle"; 它对name属性做了修改,所以当我们再次使用new Shape对象的时候 name属性就会是"Triangle"而不是"shape"
var s = new Shape();
s.name 输出"Triangle"而不是"shape";
解决方法是创建一个空的构造函数像下面这样:
创建空的构造函数F(),使F的原型继承自父对象原型,F.prototype = Shape.prototype;
使子对象的原型继承自构造函数F()的实例,由于F()继承Shape,所以TwoDShape也继承Shape,由于继承的是实例对象,
所以改变子对象和父对象中的同名属性不会影响到父对象
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; //constructor属性进行重置
TwoDShape.prototype.name = "2D shape";
function Triangle(side,height){
this.side = side;
this.height = height;
}
var F = function(){};
F.prototype = TwoDShape.prototype;
Triangle.prototype = new F();
Triangle.prototype.constructor = Triangle; //constructor属性进行重置
Triangle.prototype.name = "Triangle";
Triangle.prototype.getArea = function(){return this.side*this.height};
var s = new Shape();
s.name;