Loading

JS查看对象属性的方式

var person = {
    type: 'person',
    say: function(){
        console.log("Hellow World!")
    }
}
//以person对象为原型,创建obj对象
var obj = Object.create(person, {
    sex: {
        writable: true,
        configurable: true,
        enumerable: false, //设置sex属性为不可枚举
        value: 'male'
    },
    age: {
        writable: true,
        configurable: true,
        enumerable: true, //设置sex属性为可枚举
        value: 23
    }
});
//为obj对象创建Symbol属性
var mySymbol = Symbol();
Object.defineProperty(obj, mySymbol, {
    value: 'hello!'
});

obj.name = '张三'; //自定义属性name默认为可枚举
console.log(obj.propertyIsEnumerable('name')); //true, 成功验证name属性为可枚举

//用for…in…获取obj上全部可枚举的属性(包括自有和原型链上的)
var arr = [];
for(var key in obj){
    arr.push(key);
}
console.log(arr); //["age", "type", "say"]

//用Object.keys()获取obj上全部可枚举的自有属性
console.log(Object.keys(obj)); //["age", "name"]

//用Object.getOwnPropertyNames()获取obj上所有的属性
console.log(Object.getOwnPropertyNames(obj)); //["sex", "age", "name"]

//用Object.getOwnPropertySymbols(obj)获取obj上的Symbol属性
console.log(Object.getOwnPropertySymbols(obj));// [Symbol()]

//用Reflect.ownKeys(obj)获取obj上所有属性,包括Symb属性
console.log(Reflect.ownKeys(obj)); // ["sex", "age", "name", Symbol()]

 

posted @ 2019-01-28 15:06  Frank-Link  阅读(964)  评论(0编辑  收藏  举报