首页 > 语言 > JavaScript > 正文

javascript原型链继承用法实例分析

2024-05-06 14:46:46
字体:
来源:转载
供稿:网友

本文实例分析了javascript原型链继承的用法。分享给大家供大家参考。具体分析如下:

代码如下: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属性产生一定的负面影响。
所以,在我们完成相关的继承关系设定后,对这些对象的const属性进行相应的重置是一个非常好的习惯。如下所示:

代码如下:TwoDShape.prototype.constructor = TwoDShape; 
Triangle.prototype.constructor = Triangle;

改写:
代码如下: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; 
}

再改写(引用传递而不是值传递):
代码如下: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(){ 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选