Javascript:获取实例getter和字段名称或名称和值



我通常使用下一句话来获取所有对象字段,但我刚刚意识到这是跳过对象getter

Object.entries(myInstance) 

我也尝试过但没有结果:

Object.keys(myInstance)
Object.values(myInstance)

有什么方法可以遍历对象属性和getter?我感兴趣的是getter的名称和值,而不是函数本身。

如果类声明定义了一个方法或getter,它们将在原型上定义,并且是不可枚举的。

也就是说,它们既不会出现在Object.keysObject.getOwnPropertyNamesReflect.ownKeys中(它们不会查找原型(,也不会出现在一个for..in循环中(它跳过不可枚举的属性(。

你有三种方法:

  • 使getter可枚举:

class Foo{
/* contents of class */
}
Object.defineProperty(Foo.prototype, 'bar', {
get: () => 'baz',
enumerable: true,
configurable: false //Or true
})
for(const prop in new Foo){
console.log(prop)
}

  • 在实例上定义getter:

class Foo{
constructor() {
Object.defineProperty(this, 'bar', {
get: () => 'baz',
enumerable: false,
configurable: false //Or true
})
}
/* contents of class */
}
console.log(Object.getOwnPropertyNames(new Foo))

  • 实现自定义查找算法:

class Foo{
get bar(){return 'baz'}
/* class contents here */
}
Object.getAllPropertyNames = obj => new Set(obj != null //not null or undefined 
? [
...Reflect.ownKeys(obj),
...Object.getAllPropertyNames(Object.getPrototypeOf(obj))
]
: undefined
)
console.log(Array.from(Object.getAllPropertyNames(new Foo)))

Object.getOwnPropertyNames

来自MDN web文档:"Object.getOwnPropertyNames((方法返回所有属性的数组(包括除使用Symbol的属性外的不可枚举属性(">

您还可以使用Object.defineProperty使getter可枚举,以使用config定义实例,使其可枚举。将"this"替换为对下面对象的引用。

Object.defineProperty(this, 'getterName' {
enumerable: true,
get: function() {
return 'value'
}
}

MDN:Object.defineProperty

最新更新