(9)JavaScript學習筆記 - 對象

來源:互聯網
上載者:User

JS中的對象是一種複合資料型別,將多個資料值集中在一個單元中,允許使用名字來存取這些值。
也可以理解為:對象是一個無序的屬性集合,每個屬性都有自己的名字和值。

一、建立
[javascript] 
//直接加入一個對象直接量,是用逗號分隔開的一對對的屬性名稱和值的列表 
var empty = {}; 
var point = {x:0,y:0}; 
var circle = { x:point.x,y:point.y+1,radius:2}; 
var homer={ 
    "name":"Home Simpson", 
    "age":34, 
    "married":true, 
    "occupation":"plant operator", 
    'email':"homer@example.com" 
} 

二、對象屬性
[javascript] 
//使用 . 來存取對象的屬性 
var book = {}; 
book.title = "簡·愛"; 
book.chapter1 = new Object{}; 
book.chapter1.title = "Introduction to JavaScript"; 
book.chapter1.pages = 11; 
book.chapter2 = { title:"Lexical Structure",pages:6}; 
 
alert( 
"Outline:"+book.title+"\n\t"+ 
"Chapter1"+book.chapter1.title+"\n\t"+ 
"Chapter2"+book.chapter2.title 
); 

三、屬性的枚舉
[javascript] www.2cto.com
function DisplayProertyNames(obj){ 
    var name=""; 
    for(var name in obj){ 
    names=name+"\n"; 
    } 
    alert(names); 
} 

四、檢查屬性的存在性
//in用來測試一個屬性的存在性
if("x" in o) o.x=1;
if(o.x!==undefined) o.x=1;
//也可以這樣簡寫
if(o.doSomething) o.doSomething;

五、刪除屬性
[javascript] 
delete book.chapter2; 

六、constructor 屬性
JS中每個對象都有一個constructor屬性,引用了初始化這個對象的建構函式
[javascript] 
//可以使用以下的代碼確定一個未知值的類型 
if((typeof o=="object")&&(o.constructor==Date)) 
 
//instanceof可以檢查constructor屬性的值,所以上面的代碼也可以這樣寫 
if((typeof o=="object"&&(o instanceof Date))) 
作者:dxh_0829

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.