Javascript对象继承

[b]1. 原型继承法[/b]

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
function dw(s) {
document.write(s + "<br />");
}
//警察
function PoliceMan() {
var m_lifeEnergy = 100;
this.getLifeEnergy = function () {
return m_lifeEnergy;
}
this.Shot = function () {
m_lifeEnergy -= 1;
}
this.Repair = function() {
m_lifeEnergy += 1;
}
}
//超级警察
function SuperPoliceMan() {
this.Flight = function() {

}
}

SuperPoliceMan.prototype = new PoliceMan();

//创建一个超级警察
var pm = new SuperPoliceMan();
//显示当前生命值
dw(pm.getLifeEnergy());
//中枪生命值减1
pm.Shot();
//显示当前生命值
dw(pm.getLifeEnergy());
//飞离地面
pm.Flight();
//自我修复
pm.Repair();
//显示当前生命值
dw(pm.getLifeEnergy());
</script>
</head>
<body>

</body>
</html>


[b]2. 复制继承法[/b]

<!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>
<title></title>
<script type="text/javascript">
function dw(s) {
document.write(s + "<br />");
}
//一个一个复制父类的属性
Function.prototype.extendcopy = function(obj) {
for(var each in obj){
this.prototype[each] = obj[each];
}
}

//警察
function PoliceMan() {
var m_lifeEnergy = 100;
this.getLifeEnergy = function () {
return m_lifeEnergy;
}
this.Shot = function () {
m_lifeEnergy -= 1;
}
this.Repair = function() {
m_lifeEnergy += 1;
}
}

//超级警察
function SuperPoliceMan() {
this.Flight = function() {

}
}
//复制继承
SuperPoliceMan.extendcopy(new PoliceMan());

//创建一个超级警察
var pm = new SuperPoliceMan();
//显示当前生命值
dw(pm.getLifeEnergy());
//中枪生命值减1
pm.Shot();
//显示当前生命值
dw(pm.getLifeEnergy());
//飞离地面
pm.Flight();
//自我修复
pm.Repair();
//显示当前生命值
dw(pm.getLifeEnergy());
</script>
</head>
<body>

</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值