Can a JavaScript function return itself?

ぐ巨炮叔叔 提交于 2019-11-30 07:47:52

问题


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?


回答1:


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




回答2:


Yes.
Just return arguments.callee;


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




回答3:


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




回答4:


Even sorter that all the above is:

f=()=>f



回答5:


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



回答6:


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

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


来源:https://stackoverflow.com/questions/6959426/can-a-javascript-function-return-itself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!