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);
The syntax is simple: you can simply declare the anonymous function and make it execute by just calling it using the parenthesis at the end of the function. You can simply pass the parameters inside the immediate execution of the anonymous function as we have seen in the above example.
We write the anonymous function in Javascript by writing function() followed by the parentheses, where we may pass the parameters, and skipping the function name. Then in a pair of curly braces {}, we write our desired code. Finally, we assign this function to a variable.
Summary. Anonymous functions are functions without names. Anonymous functions can be used as an argument to other functions or as an immediately invoked function execution.
console. log(Arr. map(function(x){ return myCallback(x+2)})); In JavaScript, callbacks and anonymous functions can be used interchangeably.
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)
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