我试图在打字稿中发现对象上的吸气剂和吸气剂。我已经尝试过Object.entries()和Object.keys(),但这些都不返回getter和setter。我如何枚举这些?
编辑:这是一些显示问题的代码:
class ThingWithGetter{
myProperty = 22;
get myGetter() {return 1;}
}
const thing = new ThingWithGetter()
// Does not show getter
console.log(Object.keys(thing));
// Does not show getter
const descriptors = Object.getOwnPropertyDescriptors(thing);
console.log(Object.keys(descriptors));
// Does not show getter
console.log(Object.entries(thing))
这样做不起作用的原因是,getter位于类的原型上,该原型位于实例的原型链上,而不是实例本身。
为了显示:
class A {
get x() { return 1 }
}
aInstance = new A()
// A {}
Object.getOwnPropertyDescriptors(aInstance)
// {}
Object.getOwnPropertyDescriptors(A.prototype)
// { constructor:
// { value: [Function: A],
// writable: true,
// enumerable: false,
// configurable: true },
// x:
// { get: [Function: get x],
// set: undefined,
// enumerable: false,
// configurable: true } }
Object.getOwnPropertyDescriptors(Object.getPrototypeOf(aInstance))
// { constructor:
// { value: [Function: A],
// writable: true,
// enumerable: false,
// configurable: true },
// x:
// { get: [Function: get x],
// set: undefined,
// enumerable: false,
// configurable: true } }
Axel Rauschmayer撰写了一些有关此主题的好博客文章:
请注意,如果尝试枚举对象上的所有属性,访问器和方法,则需要递归遍历原型链,直到对象具有null
原型为止。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句