日期:2014-05-16  浏览次数:20389 次

Javascript对象继承(复制继承法)
复制继承可以说是Javascript中我使用的最多的继承方法.
复制继承是如何实现的,我们一起来看看下面的例子:
01.<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
02. 
03.<html xmlns="http://www.w3.org/1999/xhtml">
04.<head>
05.<title></title>
06.<script type="text/javascript">
07.function dw(s) {
08.document.write(s + "<br />");
09.}
10.//一个一个复制父类的属性
11.Function.prototype.extendcopy = function(obj) {
12.for(var each in obj){
13.this.prototype[each] = obj[each];
14.}
15.}
16. 
17.//警察
18.function PoliceMan() {
19.var m_lifeEnergy = 100;
20.this.getLifeEnergy = function () {
21.return m_lifeEnergy;
22.}
23.this.Shot = function () {
24.m_lifeEnergy -= 1;
25.}
26.this.Repair = function() {
27.m_lifeEnergy += 1;
28.}
29.}
30. 
31.//超级警察
32.function SuperPoliceMan() {
33.this.Flight = function() {
34. 
35.}
36.}
37.//复制继承
38.SuperPoliceMan.extendcopy(new PoliceMan());
39. 
40.//创建一个超级警察
41.var pm = new SuperPoliceMan();
42.//显示当前生命值
43.dw(pm.getLifeEnergy());
44.//中枪生命值减1
45.pm.Shot();
46.//显示当前生命值
47.dw(pm.getLifeEnergy());
48.//飞离地面
49.pm.Flight();
50.//自我修复
51.pm.Repair();
52.//显示当前生命值
53.dw(pm.getLifeEnergy());
54.</script>
55.</head>
56.<body>
57. 
58.</body>
59.</html>