Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping a JavaScript callback redefining "this"

Tags:

javascript

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?

like image 889
Salvatore Iovene Avatar asked Apr 01 '26 15:04

Salvatore Iovene


1 Answers

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.

like image 177
jAndy Avatar answered Apr 04 '26 04:04

jAndy