Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: how to return own function? [duplicate]

Tags:

javascript

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?

like image 342
Kees C. Bakker Avatar asked Sep 10 '26 16:09

Kees C. Bakker


1 Answers

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.
like image 182
Peter Olson Avatar answered Sep 13 '26 06:09

Peter Olson