Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a JavaScript function return itself?

Can I write a function that returns iteself?

I was reading some description on closures - see Example 6 - where a function was returning a function, so you could call func()(); as valid JavaScript.

So I was wondering could a function return itself in such a way that you could chain it to itself indefinitely like this:

func(arg)(other_arg)()(blah); 

Using arguments object, callee or caller?

like image 213
fbas Avatar asked Aug 05 '11 16:08

fbas


People also ask

Can a function be returned?

You can return a complex object with multiple properties. And you can return a function. a function is just a thing. In your case, returning b returns the thing, the thing is a callable function.

Should JavaScript functions always return?

It's a ground rule. JavaScript follows this rule, functions always return something. In the case where you don't want to return a value, something else exists.

Can a function return another function in JavaScript?

A JavaScript function can be passed as a return value from another function.


1 Answers

There are 2-3 ways. One is, as you say, is to use arguments.callee. It might be the only way if you're dealing with an anonymous function that's not stored assigned to a variable somewhere (that you know of):

(function() {     return arguments.callee; })()()()().... ; 

The 2nd is to use the function's name

function namedFunc() {     return namedFunc; } namedFunc()()()().... ; 

And the last one is to use an anonymous function assigned to a variable, but you have to know the variable, so in that case I see no reason, why you can't just give the function a name, and use the method above

var storedFunc = function() {     return storedFunc; }; storedFunc()()()().... ; 

They're all functionally identical, but callee is the simplest.

Edit: And I agree with SLaks; I can't recommend it either

like image 117
Flambino Avatar answered Sep 19 '22 06:09

Flambino