开发者

Cast from object to function

Suppose I have a javascript function of the form:

function(){alert("blah");}

Suppose I also have an applet, which has a method called doStuff that takes the function as a parameter:

MyApp开发者_开发问答let.doStuff(function(){alert("blah");});

Now suppose that the applet passes the function to a success or failure javascript callback function depending on the result of its calculations. In that callback function, I want to execute the function so that the user gets my exceedingly informative "blah" message:

function callback(func) {
  func();
}

However, in the example above, func is no longer considered to be of type "function" (typeof func will return "object"). Is it possible to convert func to be a function so that it can be executed? I have a number of hacks in mind that can give me what I want, but they are very ugly and I was hoping that I was missing something simple.

Any help is greatly appreciated.


Try func.call()


Using the same style code as you already have, the following should alert "called!":

function callback(func){
  func();
}
callback(function(){
  alert("called!");
});

Is MyApplet.doStuff(function(){alert("blah");}); definitely passing its argument to the callback function unchanged?


I opted to go for a different solution that isn't as ugly as I imagined it would be. The JSObject.call() java method converts all the callback function parameters to plain jane objects. So instead of passing:

function(){alert("blah")}

I now pass:

alert("blah")

or after some annoying escaping:

''alert(\''blah\'');''

Not so terrible eh? Many thanks to everyone that offered their help, it is appreciated.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜