在JS中,对象的属性分为可枚举和不可枚举,它是由属性的enumerable值决定的,true为可枚举,false为不可枚举
JS中预定义的原型属性一般是不可枚举的,而自己定义的属性一般可枚举
可以通过propertyIsEnumerable方法判断该属性是否可枚举
属性的枚举性会影响以下三个函数的结果:
for ... in ...
Object.keys()
JSON.stringify()
例子:
function Person(){
this.name = 'kong';
}
Person.prototype = {
age : 18,
job : 'student'
}
var a = new Person();
Object.defineProperty(a, 'sex', {
value : 'men',
enumerable : false //定义该属性不可枚举
})
//for in
for(var k in a){
console.log(k);
}
//name age job
//Object.keys()
console.log(Object.keys(a));
//['name']
//JSON.stringify()
console.log(JSON.stringify(a));
//{'name' : 'kong'}
//propertyIsEnumerable方法判断该属性是否可枚举
console.log(a.propertyIsEnumerable('name')); //true
console.log(a.propertyIsEnumerable('age')); //false
console.log(a.propertyIsEnumerable('sex')); //false