js之oop <三>屬性標籤

來源:互聯網
上載者:User

標籤:

讀取屬性標籤

擷取對象屬性標籤,用 Object.getOwnPropertyDescriptor方法。
getOwnPropertyDescriptor(); 參數:屬性所在對象(object),屬性名稱(string)

var obj = { code:2,element:"ele" };Object.getOwnPropertyDescriptor(obj,"code");//輸出 { value: 2, writable: true, enumerable: true, configurable: true }

getOwnPropertyDescriptor返回該屬性標籤的對象。
value      屬性值
writeable    屬性是否可寫(是否可修改)
enumerable    屬性是否可枚舉(是否在for in遍曆中出現)
configurable   屬性的其他屬性標籤是否可修改或者該屬性是否可delete
一般方式添加這四個屬性標籤預設都是true。

****************************************************************************************************************

定義屬性標籤

定義對象屬性標籤,用 Object.defineProperty()方法。
defineProperty(); 參數:目標對象(object),屬性名稱(string),屬性標籤(object json(對象字面量)格式建立)

這裡defineProperty的第三個參數的屬性包括:value,writeable,enumerable,configurable。value必須賦值,writeable,enumerable,configurable預設都為false。

var obj = {};Object.defineProperty(obj,"o_name",{    value:"obj_name",    writeable:false,    enumerable:false,    configurable:false});obj.o_name = "New_name";    //輸出 obj_name//writeable為false,所以無法修改該屬性值。delete obj.o_name;          //返回 false//configurable為false,所以無法被delete。Object.keys(obj)            //返回空集合//enumerable為false,所以無法遍曆

批量定義屬性標籤

定義對象屬性標籤,用 Object.defineProperties()方法。
defineProperties(); 參數:目標對象(object),批量屬性標籤(object json(對象子面量)格式建立)

function o(){};var o1 = new o();Object.defineProperties(o1,{a:{value:1,enumerable:true},                            b:{value:2,writable:true},                            c:{value:3,configurable:true,writable:true}});Object.getOwnPropertyDescriptor(o1,"a");//返回 { value: 1,writable: false,enumerable: true,configurable: false }Object.getOwnPropertyDescriptor(o1,"b");//返回 { value: 2,writable: true,enumerable: false,configurable: false }Object.getOwnPropertyDescriptor(o1,"c");//返回 { value: 2,writable: true,enumerable: false,configurable: true }

****************************************************************************************************************

遍曆對象屬性

遍曆對象屬性除了用for in還可以用 Object.keys()方法。
keys(); 參數:遍曆對象(object)。
keys()返回對象屬性的數組。

var obj = { a:1,b:2,c:3,d:4 };obj.e = 5;Object.keys(obj);//返回 [ ‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘ ]Object.defineProperty(obj,"e",{value:15,enumerable:false});Object.keys(obj);//返回 [ ‘a‘, ‘b‘, ‘c‘, ‘d‘ ]obj.e;  //輸出 15

 

js之oop <三>屬性標籤

聯繫我們

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