admin管理员组

文章数量:1355675

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?

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?

Share Improve this question asked Mar 9, 2016 at 1:56 Siegmund NagelSiegmund Nagel 1,3812 gold badges11 silver badges20 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 11

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

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>

本文标签: ecmascript 6Pass a Javascript getter as a parameterStack Overflow