簡單模擬javaScript物件導向

劍握在手發表於2013-12-28

<html>

<head>

<script type="text/javascript">

 

  if (!Object.create) {

    Object.create = function (o) {

       function F() {}

      F.prototype = o;

      return new F();

    };

  }

 

 function alertt(){

       ca = new cat();

       alert(ca.name);

 

       dog1=Object.create(Dog);

       dog1.shout();

 

       pig=Pig.createNew();

       pig.shout();

 

       spig = SmallPig.createNew();

       spig.shout();

}

 

 

//方法一

Pig = {

              job:"eat";//全域性靜態變數,可被多個物件共享

    createNew: function(){

      var pig = {};

                     sound = "herher";//直接定義是私有

      pig.name = "BigPig";

      pig.shout = function(){ alert(sound); };

      return pig;

    }

};

 

//繼承

SmallPig = {

       createNew: function(){

                     var pig = Pig.createNew();

                     pig.name = "SmallPig";

                     pig.shout = function(){ alert("wuher wuher"); };

      return pig;

       }

}

 

//方法二

Dog={

       shout:function(){alert("wangwang");}

}

 

//方法三

function cat(){

       this.name = "miaomiao";

}

 

</script>

</head>

<body>

 

<button id="b01" type="button" onclick="alertt()">動物叫</button>

 

</body>

</html>

相關文章