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?
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.
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.
A JavaScript function can be passed as a return value from another function.
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
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