深入理解JavaScript對(duì)象屬性
創(chuàng)建JavaScript的對(duì)象,可以通過(guò)對(duì)象.屬性名獲取值,也可以通過(guò)對(duì)象['key']獲取內(nèi)容。
使用對(duì)象['key']
,傳入的內(nèi)容都會(huì)被轉(zhuǎn)換為字符串值。
var obj = { a: 'test', b: 'test2' }; obj.a; //test obj['b'];//test2
屬性讀寫(xiě)
var obj = {
a: 'test',
b: 'test2'
};
obj.a; //test
obj['b'];//test2
屬性異常
如果讀取沒(méi)有的屬性,通常會(huì)返回undefined,如果二維值的話,會(huì)報(bào)錯(cuò)。
console.log(obj.z);//undefined
console.log(obj.z.b);//Uncaught TypeError: Cannot read property 'b' of undefined
obj.y.z = 2; // TypeError: Cannot set property 'z' of undefined
//可以通過(guò)判斷是否存在
if (obj.y) {
//存在的話則執(zhí)行
}
屬性枚舉
var key;
for (key in obj) {
console.log(obj[key]);
}
屬性刪除
使用delete關(guān)鍵字
delete obj.a;//true obj.a; // undefined
如果這個(gè)屬性設(shè)置過(guò)configurable為true,則不能刪除。
默認(rèn)創(chuàng)建的屬性,configurable為false。下面講如何設(shè)置為true。
不能刪除全局變量
var globalVal = 1; delete globalVal; // false
不能刪除函數(shù)
function fd() {}
delete fd; // false
可以刪除Window上的變量
ohNo = 1; window.ohNo; // 1 delete ohNo; // true
屬性檢測(cè)
判斷是否存在這個(gè)屬性
var obj = {
a: 'test',
b: 'test2'
};
'a' in obj;//true
'toString' in obj //true
在原型鏈上的值也可以被檢測(cè)到。
例如所有對(duì)象上都有toString屬性.
每個(gè)屬性都有一個(gè)屬性:enumerable,是否可以被檢測(cè),默認(rèn)為true,如果為false,則檢測(cè)不到這個(gè)屬性,不能遍歷。
var obj = {
a: 'test',
b: 'test2'
};
Object.defineProperty(obj, 'price', {
enumerable: false,
value: 1000
});
var key;
for (key in obj) {
console.log(obj[key])
}
//只輸出test和test2
判斷這個(gè)屬性可否被枚舉,true 可以,false不能
obj.propertyIsEnumerable('price');
設(shè)置屬性的屬性
版權(quán)聲明:
作者:applek
鏈接:http://www.51viplawyer.com/srljjsdxsx.html
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載。
THE END
