I want to inspect an instance of a JavaScript class and access its getter. In ES5, I can write this code to retrieve the getter of an object:
var obj = {
get foo () {}
};
const foo = Object.getOwnPropertyDescriptor (obj, 'foo').get;
// returns a function
However, when I try this on a class instance, my code fails:
class Foo {
get foo () {}
}
var obj = new Foo ();
const foo = Object.getOwnPropertyDescriptor (obj, 'foo').get;
// error: Cannot read property 'get' of undefined
Object.getOwnPropertyDescriptor
does not seem to work: it returns undefined
for the foo
property.
I am using Babel 6.4.5 to transpile my code from ES2015 to ES5.
Is Object.getOwnPropertyDescriptor
supposed to work on classes too? Or is this a side effect of using Babel?
EDIT I've finally switched to Object.getOwnPropertyDescriptor
as suggested
by Bergi. I describe the solution in detail in a blog post
(Enumerating methods on a JavaScript class instance).
To access the property descriptor of property, we need to use a static method provided by the Object. The Object. getOwnPropertyDescriptor method returns the property descriptor of the prop which is the property name on the obj object. Object.
getOwnPropertyDescriptor() method returns an object describing the configuration of a specific property on a given object (that is, one directly present on an object and not in the object's prototype chain). The object returned is mutable but mutating it has no effect on the original property's configuration.
A data descriptor is a property that has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both.
__proto__ is a way to inherit properties from an object in JavaScript. __proto__ a property of Object. prototype is an accessor property that exposes the [[Prototype]] of the object through which it is accessed. POSTly is a web-based API tool that allows for fast testing of your APIs (REST, GraphQL).
It does work with classes, but the instance you tried it on has no own property. Use
Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), 'foo')
Object.getOwnPropertyDescriptor(Foo.prototype, 'foo')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With