可枚举性(enumerable)是什么?
参考答案
属性的一个特性,决定它是否会被 for...in、Object.keys、JSON.stringify、展开运算符等"枚举"操作包含。
enumerable: true(字面量/赋值创建的属性默认):可被枚举;enumerable: false:不可被上述操作访问,但仍可直接访问(obj.x、in、Object.getOwnPropertyNames)。
典型不可枚举属性
Object.prototype.toString、Array.prototype 上的方法、class 的原型方法、length、内建属性。
查看
Object.getOwnPropertyDescriptor(obj, 'a').enumerable
用途
- 隐藏内部属性(序列化时不被带出);
- 避免原型方法污染遍历;
- 控制
Object.assign/展开的字段集合(它们只复制可枚举属性)。