Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: How to pass an anonymous function as a function parameter?

Tags:

javascript

I would like to write a function that accepts an anonymous function as a parameter. For example:

run('param1', function(){
    alert('execute this');
});

function run(param1, callback) {
    //now execute the callback parameter as a function
}

How can I achieve something like this?

like image 636
Andrew Avatar asked Sep 28 '10 00:09

Andrew


1 Answers

callback() would invoke it.

If you need to supply a context, do callback.apply(this, arguments). When you use .apply be aware of the current execution context, basically know what this will refer to, or your code will not work as expected if you are feeding a literal that references this inside it's function body.

like image 72
meder omuraliev Avatar answered Oct 12 '22 02:10

meder omuraliev