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
精彩评论