Completing the JavaScript callback override "this"

I know about call

and apply

in JavaScript, but I am currently following the following scenario.

I am using Benchmarkjs and it has an API defined like this:

.on(eventType, listener)

      

So, I would do for example:

/* Register the onStart callback */
suite.on('start', onStart);

      

My function onStart

is called so that this === suite

.

How can I do this to identify one of arguments

the onStart

?

My code looks something like this:

foo = function() {
   this.suite.on('start', this.onStart);
}

      

I want my function to onStart

have a link to foo

.

Any suggestions?

+3


source to share


2 answers


You can call Function.prototype.bind

to create partial applications / currency functions.

.bind()

takes a context as the first parameter, and all subsequent ones passed in parameters will be used as formal parameters to call the associated function.



suite.on( 'start', this.onStart.bind( this, foo ) );

      

The link to foo

will now be available for onStart()

as the very first argument.

+1


source


You can pass this

in onStart

by wrapping it in a function.

foo = function() {
    this.suite.on('start', function(arguments){onStart(arguments, this)});
}

      



I prefer to pass it over instead of using bind

it as bind

IE 8 and below is not supported.

0


source







All Articles