There are some function, thats do something long work and its provides callback.
someFunc: function(argument, callback, context) {
// do something long
// call callback function
callback(context);
}
In application I use this function
someFunc('bla-bla', function (context) {
// do something with this scope
context.anotherFunc();
}, this);
How to implement callback function without passing context
parameter?
Need some like this:
someFunc('bla-bla', function () {
// do something with this scope
this.anotherFunc();
}, this);
Use
Function.prototype.call
to invoke a function and manually set thethis
value of that function.Now your callback has the expected
this
value.Of course you can pass arguments like normal in the
.call
invocation.The accepted answer seems somewhat outdated. Assuming you're operating on a relatively modern browser, you can use
Function.prototype.bind
in vanilla javascript. Alternatively, if you are using underscore or jQuery, you can use_.bind
or$.proxy
respectively (which will fallback tocall
/apply
if necessary).Here is a simple demonstration of these three options:
You can find the code in a jsfiddle here: http://jsfiddle.net/yMm6t/1/ (note: ensure that the developer console is open, or you won't see any output)