Foreword
JavaScript Object acquired more property methods, but each method are different scenarios, in order to explain the situation, the following is assumed that
let c = Symbol.for('这是实例上的属性');
let e = Symbol.for('这是原型上的属性');
let obj = {a:1,b:2,[c]:5};
Reflect.setPrototypeOf(obj,{
fn:2,
[e]:8
})
Object.defineProperties(obj,{
d:{
value:6,
enumerable:false
}
})
Object.keys()
Object.keys(obj).forEach(prop=>{
console.log(prop);
})
//a
//b
Obtains an instance attribute object itself, but it does not include a symbol key
Object.getOwnPropertySymbols()
console.log('-----------------获取symbol键')
Object.getOwnPropertySymbols(obj).forEach(prop=>{
console.log(prop);
})
// -----------------
// Symbol(这是实例上的属性)
For acquiring symbol keys nor obtaining prototypes
Object.getOwnPropertyNames()
console.log('-----------------不管枚举或者不可枚举都会获取')
Object.getOwnPropertyNames(obj).forEach(prop=>{
console.log(prop);
})
//a
//b
//d
Whether or not enumerable will get, still does not include symbol keys
for…in
for(const prop in obj){
console.log(prop);
}
//a
//b
//fn
Obtaining property will still get the prototype, so we use the iterative method requires careful if required properties on the prototype, using the iterative method can add an object instance hasOwnProperty
judge
for(const prop in obj){
if(obj.hasOwnProperty(prop)){
console.log(prop);
}
}
//a
//b