javascript物件導向編程之二 聊聊對象的事

來源:互聯網
上載者:User

javascript是基於對象的程式設計語言。從window到document,從方法到類,從object到Array都是對象。

先看一下JSON(javascript object notation)對象,JSON是一種指令碼操作時常用的資料交換格式對象,相對於XML來說JSON是一種比較輕量級的格式,在一些 intelligence的IDE中還可以方便的通過點操作JSON對象中的成員。

JSON是一種鍵/值對方式來描述內部成員的格式,其內部成員可以是幾乎任何一種類型的對象,當然也可以是方法、類、數組,也可以是另外一個JSON對象。

var student = {
       Name: "張三",
       Age: 20,
       Hobby: "讀書",
       Books: [
         {
           BookName : "C#" ,
           Price : 70
         },
         {
           BookName : "Java" ,
           Price : 70
         },
         {
           BookName : "Javascript" ,
           Price : 80
         }
       ]
};

上面代碼用JSON對象描述了一個學生的資訊,他有姓名、年齡、愛好、書集等。在訪問該學生對象時,可以通過student變數來操作學生的資訊。

var stuInfo = "姓名:" + student.Name +
            ",年齡:" + student.Age +
            ",愛好:" + student.Hobby +
            ",擁有的書:" +
                       student.Books[0].BookName + "、" +
            student.Books[1].BookName + "、" +
                       student.Books[2].BookName;
alert(stuInfo);

這樣的操作方式風格和C#也非常相像。以上的代碼是靜態構造出了學生對象,學生對象的結構就確定了。在其它的程式設計語言中一般對象結構一旦確定就不能很方便的進行修改,但是在javascript中的對象結構也可以方便的進行改動。下面為student對象添加一個Introduce方法來做自我介紹。

student.Introduce = function() {
       var stuInfo = "姓名:" + this.Name +
              ",年齡:" + this.Age +
              ",愛好:" + this.Hobby +
              ",擁有的書:" +
              this.Books[0].BookName + "、" +
              this.Books[1].BookName + "、" +
              this.Books[2].BookName;
       alert(stuInfo)
};
student.Introduce();

student對象原來並沒有Introduce方法,第一次為student.Introduce賦值會在student對象中建立一個新的成員,後面如果再為student.Introduce賦值則會覆蓋上一次所賦的值。當然我們這的值是一個function。也可以用類似索引的方式來新增成員。

student["Introduce"] = function() {
      ……
};

student.Introduce();

當然添加的成員也可以刪除掉。刪除掉之後則成為undefined,再訪問該成員時則不支援。

delete student.Introduce;
student.Introduce();
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.