我的java歷程

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

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

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

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

          2. 對象中的一個方法實現
          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 閱讀(1940) 評論(0)  編輯  收藏 所屬分類: JavaScript

          主站蜘蛛池模板: 黎城县| 沂水县| 米易县| 岳阳县| 花莲市| 电白县| 文成县| 长沙县| 民勤县| 光泽县| 湟中县| 夏津县| 玛多县| 许昌县| 临泉县| 安国市| 安阳市| 高台县| 芒康县| 马边| 贵溪市| 昌邑市| 宁海县| 兴仁县| 邹城市| 逊克县| 临安市| 金秀| 鹤庆县| 景德镇市| 凤凰县| 房山区| 额尔古纳市| 望江县| 乡宁县| 商水县| 措美县| 观塘区| 海门市| 祁东县| 体育|