Javascript对象继承(复制继承法)
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> <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>