Siegmund Nagel
Siegmund Nagel

Reputation: 1381

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?

Upvotes: 7

Views: 1919

Answers (2)

Amadan
Amadan

Reputation: 198476

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

Upvotes: 11

blurfus
blurfus

Reputation: 14031

Not sure I understood you do you mean a way to define the function and pass it later to another one (as a function) to be invoked later?

something like this?

var myFunc = function() {
  console.log('func');
  document.getElementById('result').innerHTML='func';
}

console.log( 'start');
  document.getElementById('result').innerHTML='start';

setTimeout( myFunc, 3000 );
console.log( 'end');
  document.getElementById('result').innerHTML='end';
<h1 id='result'>default</h1>

Upvotes: 0

Related Questions