Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a Javascript getter as a parameter

I have an ecma6/es2015 class with a getter defined like so:

get foo() { return this._foo; }

What I'd like to be able to do is pass that function as a parameter. Making a call like so:

someFunction(myClass.foo); 

will simply invoke the function. Is there a clean way I can pass the method without invoking it and then invoke in the pass I'm passing it into?

like image 437
Siegmund Nagel Avatar asked Mar 09 '16 01:03

Siegmund Nagel


1 Answers

I assume you'll have to wrap it into an anonymous function to keep it from getting executed:

someFunction(() => myClass.foo);

Or, you can get the getter function itself, but it is less readable than the above:

someFunction(Object.getOwnPropertyDescriptor(myClass, 'foo').get);
like image 77
Amadan Avatar answered Sep 24 '22 02:09

Amadan