'Invoke JavaScript function with argument via pointer?

How can you invoke a function in JavaScript, while passing in arguments, using a function pointer?

Example:

function foo (a, callback) {    
        jQuery.post('/soon/check.json', { var:a }, function(resp) {
             callback(resp);
    }); 
}

function process_json(resp) {
  // Do something with resp
}

foo(bar, process_json);

process_json never gets invoked. Looking in Firebug, the string process_json is getting passed into foo, but I assumed this represents a pointer to the function process_json.

In Javascript, is it not possible to invoke functions via pointers and pass in arguments?



Solution 1:[1]

var process_json = function(resp) {
  // Do something with resp
}

Solution 2:[2]

Try this: http://jsfiddle.net/26naf/

Function alert is passed to foo by reference:

function foo(fref)
{
   fref("hi world");
}

foo(alert);

And it works as you see.

Solution 3:[3]

Of course you can pass in functions as callbacks, in fact by doing

jQuery.post('/soon/check.json', { var:a }, function(resp) {...

You are passing a callback that will be called after the post.

So the problem is somewhere else. Is the anonymous function passed to $.post really called ?

Hope this will help

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kasturi
Solution 2 c-smile
Solution 3 sitifensys