我想定义一个自执行的匿名函数,但让它用不同的参数运行几次。
(function(x){ console.log(x*x)})(2)
// output: 4
// I know this syntax is wrong, I am
// demonstrating how I would imagine it being implemented
(function(x){ console.log(x*x)})(2)(5)
// output is error, desired output: 4{Newline}25
这可能吗?
编辑:根据@Charmander 的回答,似乎有可能 几乎肯定是个坏主意,但这正如我所料...
(function(x){ console.log(x*x); return arguments.callee})(2)(5)
最佳答案
您可以将匿名函数存储在变量中。
var someFunction = function(x){
console.log(x*x);
};
someFunction(5);
someFunction(6);
或者,如果您真的想使它成为立即调用的函数表达式 (iife),您可以让函数返回自身。
(function(x){
console.log(x*x);
return arguments.callee;
})(5)(6);
关于javascript - 是否可以执行两次匿名函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11423490/