六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 36|回复: 0

Javascript中的利用原形链和对象冒充创建类

[复制链接]

升级  10%

17

主题

17

主题

17

主题

秀才

Rank: 2

积分
65
 楼主| 发表于 2013-2-7 16:14:58 | 显示全部楼层 |阅读模式
看到一个曾经搞过web的人的blog中说到如果学Javascript不懂原形链,就太遗憾了,所以当自己看《javascript高级程序设计》时就留意了一下,说实话,下面的代码很简单,但是不是很懂所谓的原形链和对象冒充之类的东西
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=gb2312" http-equiv="Content-Type" />
<title>继承机制的实现--实例</title>
<script type="text/javascript">
function Polygon(iSides){
this.sides=iSides;
}
Polygon.prototype.getArea=function(){
return 0;
};
function Triangle(iBase,iHeight){
Polygon.call(this,3);
this.base=iBase;//设置基本的边数
this.height=iHeight;
}
Triangle.prototype=new Polygon();
Triangle.prototype.getArea=function(){
return 0.5*this.base*this.height;
};
function Rectangle(iWidth,iHeight){
Polygon.call(this,4);
this.width=iWidth;
this.height=iHeight;
}
Rectangle.prototype=new Polygon();
Rectangle.prototype.getArea=function(){
return this.width*this.height;
};
var triangle=new Triangle(12,4);
var rectangle=new Rectangle(22,10);
alert("三角形的边数:"+triangle.sides);
alert("三角形的底边12,高4,面积为:"+triangle.getArea());
alert("四边形的边数:"+rectangle.sides);
alert("四边形的长22,宽10,面积为:"+rectangle.getArea());
</script>
</head>
<body>
</body>
</html>
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表