DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> JavaScript學習筆記:創建對象和構造類
JavaScript學習筆記:創建對象和構造類
編輯:關於JavaScript     

網頁制作poluoluo文章簡介:JavaScript學習筆記:創建對象和構造類.

創建一個對象
Java代碼
 <script type="text/javaScript">
   var newObject=new Object();
   //創建一個對象
    newObject.firstName="frank";
    //增加一個firstName屬性
    newObject.sayName=function(){
        alert(this.firstName);
    }
     //添加一個sayName方法
//調用sayName方法
//    newObject.sayName();
//    newObject["sayName"]();
    var FirstName=newObject["firstName"];
    var whatFunction;
//    if(whatVolume==1){
//        whatFunction="sayName";
//    }else if(whatVolume==2){
//        whatFunction="sayLoudly"
//    }
//    newObject[whatFunction]();
    function sayLoudly(){
        alert(this.firstName.toUpperCase());
    }
    newObject.sayLoudly=sayLoudly;
    //另一種方式添加方法
    newObject["sayLoudly"]();
 </script>

利用json(javaScript Object Notation)創建對象和上面同樣的效果。
Java代碼
   function sayLoudly(){
        alert(this.firstName.toUpperCase());
    }
    var newObject={
        firstName:"frank",
        sayName:function(){alert(this.firstName);},
        sayLoudly:sayLoudly
    };
//也可以這樣
   var newObject={
        firstName:"frank",
        sayName:function(){alert(this.firstName);},
        sayLoudly:sayLoudly,
        lastName:{
            lastName:"ziggy",
            sayName:function(){alert(this.lastName);}
        }
    };
    newObject.lastName.sayName();

這樣也ok
Java代碼
   function sayLoudly(){
        alert(this.name.toUpperCase());
    }
   function sayName(){
       alert(this.name);
   }
    var newObject={
        name:"frank",
        sayName:sayName,
        sayLoudly:sayLoudly,
        lastName:{
            name:"ziggy",
            sayName:sayName
        }
    };
    newObject.lastName.sayName();

JavaScript 中的類,還有構造方法。。。
Java代碼
   function newClass(){
        alert("constructor");
        this.firstName="frank";
        this.sayName=function(){alert(this.firstName);}
       // return this;
    }
    //var nc=newClass();
    var nc=new newClass();
    //nc.firstName="ziggy";  is ok
    nc.sayName();

還可以這樣來構造類
Java代碼
   function newClass(){
     this.firstName="frank";
   }
    newClass.prototype.sayName=function(){
        alert(this.firstName);
    }
    var nc=new newClass();
    nc.firstName="ziggy";
    nc.sayName();
    var nc2=new newClass();
    nc2.sayName();

一般用prototypes來添加方法,這樣不管有多少個實例,在內存中只有一個sayName方法。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved