对象属性方法总结

总结一下方便记忆

  • in 操作符 所有属性都可以访问到,下面就不提及in操作符了
  • 继承属性
    • 只有for in 可以访问
  • 不可枚举属性
    • 只有Object(Reflect).getOwnPropertyXXXX静态方法可以访问到
方法 不可枚举属性 继承属性 symbol属性 自身属性
in
for…in
JSON.stringfy()
Object.assign()
… 扩展运算符
Object.keys()、Object.values()、Object.entries()
Object.getOwnPropertyNames()
Object.getOwnPropertySymbols(obj)
Reflect.ownKeys(obj)
Object.getOwnPropertyDescriptor(s)
Object.hasOwn(s)
Object.prototype.hasOwnProperty(s)

下面是验证代码,首先创建一个测试对象,拥有

  • self自身属性
  • parent继承属性
  • sym symbol属性
  • noEnumerable 不可枚举属性
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const parent = {
parent: 'parent'
}
const sym = Symbol("sym")
// 很重要的一个点
// 在对象的内部,使用 Symbol 值定义属性时,Symbol 值必须放在方括号之中
const child = {
self: 'self',
[sym]: "Symbol"
}
Object.setPrototypeOf(child, parent)

Object.defineProperty(child, 'noEnumerable', {
enumerable: false,
value: 0
})

测试代码如下,在nodejs 14+环境下运行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
console.log("\n for ... in \n");

for (const key in child) {
console.log(key);
}

console.log("\n in \n");

console.log('parent' in child);
console.log('self' in child);
console.log('noEnumerable' in child);
console.log(sym in child);

console.log("\n Object.keys \n");

for (const key of Object.keys(child)) {
console.log(key);

}

console.log("\n Object.getOwnPropertyNames \n");

console.log(Object.getOwnPropertyNames(child));

console.log("\n Object.getOwnPropertySymbols \n");

console.log(Object.getOwnPropertySymbols(child));

console.log("\n Reflect.ownKeys \n");

console.log(Reflect.ownKeys(child));

console.log("\n JSON.stringify \n");

console.log(JSON.stringify(child));
console.log(JSON.parse(JSON.stringify(child)));

console.log("\n Object.assign \n");

console.log(Object.assign(child));
console.log(Object.assign({}, child));

console.log("\n 扩展运算符 ... \n");

console.log({ ...child });

console.log("\n Object.getOwnPropertyDescriptors() \n");

console.log(Object.getOwnPropertyDescriptors(child));

运行结果如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
 for ... in 

self
parent

in

true
true
true
true

Object.keys

self

Object.getOwnPropertyNames

[ 'self', 'noEnumerable' ]

Object.getOwnPropertySymbols

[ Symbol(sym) ]

Reflect.ownKeys

[ 'self', 'noEnumerable', Symbol(sym) ]

JSON.stringify

{"self":"self"}
{ self: 'self' }

Object.assign

{ self: 'self', [Symbol(sym)]: 'Symbol' }
{ self: 'self', [Symbol(sym)]: 'Symbol' }

扩展运算符 ...

{ self: 'self', [Symbol(sym)]: 'Symbol' }

Object.getOwnPropertyDescriptors()

{
self: {
value: 'self',
writable: true,
enumerable: true,
configurable: true
},
noEnumerable: { value: 0, writable: false, enumerable: false, configurable: false },
[Symbol(sym)]: {
value: 'Symbol',
writable: true,
enumerable: true,
configurable: true
}
}