js對象字面量

來源:互聯網
上載者:User

對象字面量的輸出方式以及定義好處

1.對象字面量的輸出方式有兩種:傳統的‘。’,以及數組方式,只不過用數組方式輸出時,方括弧裡面要用引號括起來,如

var box = {   name:’abc’;   age:28};alert(box[‘name’]);

給對象定義方法,

A:如果用傳統定義對象的方式,就需要先定義方法,然後再把這個方法名賦值給對象的一個屬性如果要調用這個方法不加括弧,就是返回方法代碼;如果要調用這個方法該對象屬性後面加上括弧,就得到方法的傳回值

function objrun(){       return ‘123’;}var box = new Object();box.name=’abc’;box.age = 28;box.run = objrun;alert(box.run());              //結果為123// alert(box.run);              //結果為function objrun(){                                                               return ‘123’;}//如果box.run = objrun();//alert(box.run);              //結果為123,如果帶上圓括弧,就報錯啦

B:用字面量定義,只需要直接在對象的這個屬性上,寫function就行,這個function上面沒有函數名,他是個匿名函數,那怎麼調用這個方法呢,用對象的這個屬性名稱,要調用方法,同上就行

如:

var box = {   name:’abc’,   age:28,   run:function(){              return ‘123’;}}alert(box.run());

2.對象字面量的定義方式,可以輕鬆搞定函數大量參數需要一一對應輸出的情況。他的對策就是給函數傳入一個對象,而這個對象是用字面量的方式定義的,屬性和值對應的方式可以一目瞭然他們的關係,因為函數只是一段代碼,必須調用才能執行

如:

function AA(obj){      alert(obj.name);       alert(obj.age);}var obj = {      name: 'abc',      age: 28}AA(obj);

 

 

js對象字面量的demo
/** * @author zhanghua */var literal = {    add: function(){        alert("add");    },    del: function(){        alert("delete");    },    update: function(){        alert("update");    },    name: "zhangsan",    callLiteral: function(){        // 對於當前字面量對象的調用,要加this關鍵字        this.add();    }};

html檔案:

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">    <head>        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />        <title>Literal--字面量</title>        <script type="text/javascript" src="jslib/literal.js"></script>    </head>    <body>        <input type="button" value="add" onclick="javascript:literal.add()"/>        <input type="button" value="delete" onclick="javascript:literal.del()"/>        <input type="button" value="update" onclick="literal.update()"/>        <input type="button" value="name" onclick="javascript:alert(literal.name)"/>        <input type="button" value="name" onclick='javascript:alert(literal["name"])'"/>        <input type="button" value="caller" onclick='javascript:literal.callLiteral()'"/>    </body></html>

 

相關文章

聯繫我們

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