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).
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).
-
The examples are pletely different. Your first example creates an object that has a
foo
getter, the second one creates an object that has a prototype which has afoo
getter. – a better oliver Commented Jan 26, 2016 at 15:40 - Ah, yes. I have ovelooked that! I've still to get my mind around how ES6 classes get mapped to ES5. – Pierre Arnaud Commented Jan 26, 2016 at 15:52
-
"I've still to get my mind around how ES6 classes get mapped to ES5"
class Foo { constructor() { /*constructor*/ } method() {} }
, is (almost) the same asfunction Foo() { /*constructor*/ } Foo.prototype.method = function() {};
, except that methods are not enumerable. – Felix Kling Commented Jan 26, 2016 at 16:03
1 Answer
Reset to default 26It 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')