示例
<script>
//constructor
function Shape(){}
//augment(扩展) prototype
Shape.prototype.name='Shape';
Shape.prototype.toString= function () {
return this.name;
}
//another constructor
function TwoDShape(){}
//take care of inheritance 构建继承关系
TwoDShape.prototype=new Shape();
TwoDShape.prototype.constructor=TwoDShape;
//augment prototype 扩展原型对象
TwoDShape.prototype.name='2D Shape';
</script>
JS是一种完全依靠对象的语言,所以没有类的概念,不能像Java那样直接继承构造器,而是通过new Shape()构造一个实体,通过实体属性完成相应的操作,继承实现后,我们对Shape()所进行的任何修改都不会影响TwoDShape(),Because我们继承的只是有构造器创建的实体
只继承于原型
function Shape(){}
Shape.prototype.name='Shape';
Shape.prototype.toString=function() {
return this.name;
}
function TwoDShape(){}
TwoDShape.prototype=Shape.prototype;
TwoDShape.prototype.constructor=TwoDShape;
TwoDShape.prototype.name='2D Shape';
function Triangle(side,height){
this.side=side;
this,height=height;
}
Triangle.prototype=TwoDShape.prototype;
Triangle.prototype.constructor=Triangle;
Triangle.prototype.name='Triangle'
Triangle.prototype.getArea=function(){
return this.side*this.height/2;
}
这种方法效率更高,仅通过原型就完成继承关系的构建,但是若子对象与父对象指向的是同一个对象,则子对象修改会影响父对象
var my=new Triangle(5,10)
my.toString()
"Triangle"
var s=new Shape()
s.toString()
"Triangle"
创建临时构造器
function Shape(){}
Shape.prototype.name='Shape';
Shape.prototype.toString=function() {
return this.name;
}
function TwoDShape(){}
// TwoDShape.prototype=Shape.prototype;
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;
}
// Triangle.prototype=TwoDShape.prototype;
var E=function(){}
E.prototype=TwoDShape.prototype;
Triangle.prototype=new E();
Triangle.prototype.constructor=Triangle;
Triangle.prototype.name='Triangle'
Triangle.prototype.getArea=function(){
return this.side*this.height/2;
}
这种写法子对象不会覆盖父对象
var my=new Triangle(5,10)
my.toString()
"Triangle"
var s=new Shape()
s.toString()
"Shape"
简化代码,将继承部分封装成函数
function extend(Child,Parent){
var F=function(){};
F.prototype=Parent.prototype;
Child.prototype=new F();
Child.prototype.constructor=Child;
Child.uber=Parent.prototype;//子对象访问父对象的方式
}
function Shape(){}
Shape.prototype.name='Shape';
Shape.prototype.toString=function(){
var con=this.constructor;
return con.uber?con.uber.toString()+','+this.name:this.name;
}
function TwoDShape(){}
extend(TwoDShape,Shape);
TwoDShape.prototype.name='2D Shape';
function Triangle(side,height){
this.side=side;
this.height=height;
}
extend(Triangle,TwoDShape);
Triangle.prototype.name='Triangle';
Triangle.prototype.getArea=function(){
return this.side*this.height/2;
}