我的java歷程

          在JavaScript中使用prototype擴展對象屬性和方法

          在JavaScript中使用prototype對象擴展對象屬性和方法

          JavaScript是基于對象的程序開發(fā)語言,在JavaScript中可以創(chuàng)建對象和函數(shù),但創(chuàng)建好了的對象在需要時也可以使用prototype對象對其屬性和方法進行擴展。

          1. 定義一個對象
          function person(name,age,sex){
          ?this.name=name;
          ?this.age=age;
          ?this.sex=sex;
          ?this.display=display;
          }

          2. 對象中的一個方法實現(xiàn)
          function display(){
          ?var str="Person: \n";
          ?if(this.name != null)
          ??str+="name: "+this.name+"\n";
          ?if(this.age != null)
          ??str+="age: "+this.age+"\n";
          ?if(this.sex != null)
          ??str+="sex: "+this.sex+"\n";
          ?alert(str);
          }

          3. 利用prototype對對象的屬性進行擴展
          person.prototype.address="BeiJing Road";

          4. 利用prototype對對象的方法進行擴展
          person.prototype.showInfo=function(){
          ?var str="Person: \n";
          ?if(this.name != null)
          ??str+="name: "+this.name+"\n";
          ?if(this.age != null)
          ??str+="age: "+this.age+"\n";
          ?if(this.sex != null)
          ??str+="sex: "+this.sex+"\n";
          ?if(this.address != null)
          ??str+="address: "+this.address+"\n";
          ?alert(str);
          }

          5. 使用:

          var man= new person("Jack",20);
          man.display();
          man.showInfo();

          6.擴展window方法,不用加prototype

          <html>
          <head>
          <title>無標題文檔</title>
          <script language="javascript">
          ?<!--
          ?function fullScreen(){
          ?window.moveTo(0,0);
          ?window.outerWidth=screen.width;
          ?window.outerHeight=screen.height;
          }

          window.maximize=fullScreen;
          ?//-->
          </script>
          </head>

          <body>
          <form>
          ?<input type="button" value="click me" onClick="window.maximize();">
          </form>
          </body>
          </html>

          posted on 2006-12-09 21:13 landril 閱讀(1941) 評論(0)  編輯  收藏 所屬分類: JavaScript


          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導航:
           
          主站蜘蛛池模板: 内丘县| 九江市| 兴安县| 安吉县| 增城市| 虎林市| 江永县| 涞源县| 宝丰县| 景泰县| 汪清县| 焦作市| 凤台县| 巢湖市| 通许县| 合江县| 弋阳县| 正蓝旗| 金平| 白玉县| 嘉祥县| 永年县| 永顺县| 额尔古纳市| 阿拉善右旗| 罗平县| 磐安县| 洛川县| 林甸县| 田林县| 轮台县| 安新县| 乌拉特后旗| 兴安县| 阿克陶县| 丰宁| 浦城县| 阜阳市| 射阳县| 桃源县| 舞钢市|