Can A Javascript Function Return Itself?
Solution 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
Solution 2:
Yes.
Just return arguments.callee;
However, this is likely to result in very confusing code; I do not recommend it.
Solution 3:
You can do what you want as following:
// Do definition and execution at the same time.var someFunction = (functionsomeFunction() {
// do stuffreturn 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
Solution 4:
Even sorter that all the above is:
f=()=>f
Solution 5:
There is a simple way to achieve this doing the following:
let intArr = [];
functionmul(x){
if(!x){
return intArr.reduce((prev, curr) => prev * curr)
}
intArr.push(x);
return mul;
}
console.log(mul(2)(4)(2)()); => outputs 16
Post a Comment for "Can A Javascript Function Return Itself?"