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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With