我的java歷程

          在JavaScript中使用prototype擴(kuò)展對象屬性和方法

          在JavaScript中使用prototype對象擴(kuò)展對象屬性和方法

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

          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對對象的屬性進(jìn)行擴(kuò)展
          person.prototype.address="BeiJing Road";

          4. 利用prototype對對象的方法進(jìn)行擴(kuò)展
          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.擴(kuò)展window方法,不用加prototype

          <html>
          <head>
          <title>無標(biāo)題文檔</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 閱讀(1935) 評論(0)  編輯  收藏 所屬分類: JavaScript


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


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 南城县| 长春市| 北碚区| 平南县| 瑞安市| 广丰县| 商水县| 耒阳市| 达日县| 宝鸡市| 福州市| 五河县| 库尔勒市| 梁河县| 龙江县| 班玛县| 铜山县| 买车| 灌云县| 盐亭县| 嘉义市| 石台县| 安宁市| 德钦县| 万荣县| 南康市| 平远县| 富顺县| 金阳县| 竹北市| 乐东| 喜德县| 乐至县| 当阳市| 十堰市| 库伦旗| 贡嘎县| 上饶市| 麻阳| 靖安县| 尚义县|