Issue
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
In Javascript, is it not possible to invoke functions via pointers and pass in arguments?
It most certainly is possible to do this. Everything about your code looks just fine to me. Are you sure that the $.post()
callback (the anonymous function) is being called? Is bar
undefined when foo
is invoked?
To clarify, we need to invoke a function using a string — not a function pointer. Is this possible?
Yes. If the function is defined globally, you can invoke it as a property on the window
object, like so:
function foo () { /* snip */ }
var fn_name = 'foo';
window.foo(); // works
window['foo'](); // works
window[fn_name](); // also works
Answered By – Matt Ball
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0