There are some function, thats do something long work and its provides callback.
someFunc: function(argument, callback, context) {
// do something long
// c
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 to call
/apply
if necessary).
Here is a simple demonstration of these three options:
// simple function that takes another function
// as its parameter and then executes it.
function execute_param(func) {
func();
}
// dummy object. providing an alternative context.
obj = {};
obj.data = 10;
// no context provided
// outputs 'Window'
execute_param(function(){
console.log(this);
});
// context provided by js - Function.prototype.bind
// src: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
// outputs 'Object { data=10 }''
execute_param(function(){
console.log(this);
}.bind(obj));
// context provided by underscore - _.bind
// src: http://underscorejs.org/#bind
// outputs 'Object { data=10 }'
execute_param(_.bind(function(){
console.log(this);
},obj));
// context provided by jQuery - $.proxy
// src: http://api.jquery.com/jQuery.proxy/
// outputs 'Object { data=10 }'
execute_param($.proxy(function(){
console.log(this);
},obj));
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)
Use Function.prototype.call
to invoke a function and manually set the this
value of that function.
someFunc: function(argument, callback, context) {
callback.call(context); // call the callback and manually set the 'this'
}
Now your callback has the expected this
value.
someFunc('bla-bla', function () {
// now 'this' is what you'd expect
this.anotherFunc();
}, this);
Of course you can pass arguments like normal in the .call
invocation.
callback.call(context, argument);