Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot get property descriptor of a class property

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).

like image 304
Pierre Arnaud Avatar asked Jan 26 '16 15:01

Pierre Arnaud


People also ask

How do you become a property descriptor?

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.

What is the use of object get on property descriptors?

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.

What are descriptors in JavaScript?

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.

What is __ proto __ JS?

__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).


1 Answers

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')
like image 149
Bergi Avatar answered Sep 29 '22 13:09

Bergi