开发者

Javascript: how to return own function? [duplicate]

This question already has answers here: 开发者_如何学运维 Closed 11 years ago.

Possible Duplicate:

Can a JavaScript function return itself?

Consider the following javascript function:

var x = function(msg) {
    alert(msg);
    return x;
};

x('Hello')('World!');

This wil alert 'Hello' and 'World!'. Now I would like to rewrite the function without using a var x into something like:

(function(msg)
{
    alert(msg);
    return this;
})('Hello')('World');

But this doesn't work. What am I doing wrong? How can I return my own function from the function?


You can use arguments.callee to return the current function:

(function(msg) {
  alert(msg);
  return arguments.callee;
})('Hello')('World');

See it in action here.

You can also name the function and reference it by it's name, like this:

(function showMessage(msg) {
  alert(msg);
  return showMessage;
})('Hello')('World');

See this on jsFiddle.

EDIT: You asked what the best approach is. The answer is: it depends.

Since arguments.callee is deprecated in ECMAScript, that may be a reason to not use it. The second approach is more readable and complies with the standard in strict mode. However, arguments.callee does have some advantages:

  • It works on anonymous functions
  • You can rename the function without having to change the code inside
  • You can reuse the code without having to adjust it for the name of the function it is inside.


Is something like this acceptable?

(function doAlert(msg) {
    alert(msg);
    return doAlert;
}('Hello')('World'));

http://jsfiddle.net/FishBasketGordo/c33EG/


Change this for arguments.callee

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜