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

Javascript对象继承
1. 原型继承法
<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>  


2. 复制继承法
<!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>