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.calleeto return the current function:See it in action here.
You can also name the function and reference it by it’s name, like this:
See this on jsFiddle.
EDIT: You asked what the best approach is. The answer is: it depends.
Since
arguments.calleeis 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.calleedoes have some advantages: