I know about call and apply in JavaScript, but I'm currently stuck with the following scenario.
I'm using Benchmarkjs, and it has an API defined like this:
.on(eventType, listener)
So I'd do, for instance:
/* Register the onStart callback */
suite.on('start', onStart);
My onStart function will be called so that this === suite.
How can I do so that I can define one of the arguments of onStart?
My code is something like this:
foo = function() {
this.suite.on('start', this.onStart);
}
I'd like my onStart function to have a reference to foo.
Any suggestions?
You can invoke Function.prototype.bind for creating partial applications / curried functions.
.bind() takes the context as first parameter and all following passed in parameters will be used as formal parameters for the bound function invocation.
suite.on( 'start', this.onStart.bind( this, foo ) );
The reference to foo will now be available to onStart() as very first argument.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With