一个好的做法是通过循环遍历
Object.getOwnPropertyNames()
的返回值来实现。这将捕捉到可枚举和隐藏属性,但不会包括符号,并且它已经排除了继承属性。值得注意的是,在使用任何这些答案中的方法删除属性之前,该属性必须是
configurable
的。如果你想要同时捕捉符号,可以添加
Object.getOwnPropertySymbols()
。
const obj = Object.create( Object.prototype, {
visibleProperty: {
value: 'visibleProperty',
enumerable: true,
configurable: true,
},
hiddenProperty: {
value: 'hiddenProperty',
configurable: true,
},
[ Symbol( 'symbolProperty' ) ]: {
value: 'symbolProperty',
configurable: true,
},
visibleMethod: {
value: () => 'visibleMethod',
enumerable: true,
configurable: true,
},
hiddenMethod: {
value: () => 'hiddenMethod',
configurable: true,
},
[ Symbol( 'symbolMethod' ) ]: {
value: () => 'symbolMethod',
configurable: true,
},
} );
for( const key of Object.getOwnPropertyNames( obj ) ) delete obj[ key ];
console.log( Object.getOwnPropertyDescriptors( obj ) );
这将删除除符号标识的属性之外的所有内容,因此最后一行将产生以下输出:
{
[Symbol(symbolProperty)]: {
value: 'symbolProperty',
writable: false,
enumerable: false,
configurable: true
},
[Symbol(symbolMethod)]: {
value: [Function: value],
writable: false,
enumerable: false,
configurable: true
}
}