开发者

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 ch开发者_JAVA百科ain it to itself indefinitely like this:

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

Using arguments object, callee or caller?


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


Yes.
Just return arguments.callee;


However, this is likely to result in very confusing code; I do not recommend it.


You can do what you want as following:

// Do definition and execution at the same time.
var someFunction = (function someFunction() {

    // do stuff
    return someFunction
 })();

 console.log(someFunction)

arguments.callee is not supported in JavaScript strict mode.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode


Even sorter that all the above is:

f=()=>f


There is a simple way to achieve this doing the following:

let intArr = [];
function mul(x){
    if(!x){
        return intArr.reduce((prev, curr) => prev * curr)
    }
    intArr.push(x);
    return mul;
}

console.log(mul(2)(4)(2)()); => outputs 16


It is also possible just to return the argument the self invokable function like

console.log( (function(a) {  return a; })(1) ); // returns 1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜