开发者

Invoke JavaScript function with argument via pointer?

开发者 https://www.devze.com 2023-03-06 13:26 出处:网络
How can you invoke a function in JavaScript, while passing in arguments, using a function pointer? Example:

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开发者_如何学JAVA: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?


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


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


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消