JS - 对象(2)

属性操作

getOwnPropertyDescriptor: 获取属性中的标签

var descriptor = Object. getOwnPropertyDescriptor(Object, 'prototype');
descriptor.configurable; // false

属性监测

var cat = new Object;
cat.legs = 4;
cat.name = 'kitty';

'legs' in cat; // true
'abc' in cat; // false
'toString' in cat; // true, inherited prototype!!!

cat.hasOwnPrototype('legs'); // true

cat.propertyIsEnumerable('legs'); // true,是否可枚举
cat.propertyIsEnumerable('toString'); // false

字面量或 new Object 创建的对象,默认 可枚举,可写,可 delete
defineProperty 默认全是 false

Object.defineProperty(cat, 'price', {enumerable: false, value: 1000});
cat.propertyIsEnumerable('price'); // false
cat.hasOwnProperty('price'); // ture

if(cat && cat.legs) {
    cat.legs *= 2;
}

//不写严格等于 null == undefined
if(cat.legs != undefined) {
    // !== undefined, or, !== null
}

if(cat.legs ! == undefined) {
    // only if cat.legs is not undefined
}

属性枚举

var o = {x: 1, y: 2, z: 3};
'toString' in o; // true
o.propertyIsEnumerable('toString'); // false
var key;
for(key in o) {
    console.log(key); // x, y, z
}

var obj = Object.create(o);
obj.a = 4;
var key;
for(key in obj) {
    console.log(key); // a, x, y, z
}

var obj = Object.create(o);
obj.a = 4;
var key;
for(key in obj) {
    if(obj.hasOwnProperty(key)) {
        console.log(key); //a
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容