一步定义和调用功能

qui*_*uis 50 javascript recursion functional-programming iife

有没有一种方法可以在Javascript中定义一个函数并立即调用它,以一种允许它重用的方式?

我知道你可以做一次性的匿名功能:

(function(i) {
    var product = i * i;
    console.log(product);
    // Can't recurse here because there's no (ECMA standard) way for the 
    // function to refer to itself
}(2)); // logs 4
Run Code Online (Sandbox Code Playgroud)

或者你可以命名一个函数然后调用它:

function powers(i) {
    var product = i * i;
    console.log(i * i);
    if (product < 1e6) { powers(product) };
}

powers(2); // Logs 4, 16, 256...
Run Code Online (Sandbox Code Playgroud)

但是,有一种更清晰的方法可以一次性定义和调用函数吗?有点像两个例子的混合?

不能做到这一点并不妨碍我做任何事情,但感觉它是一种很好的表达方式来编写需要运行的递归函数或函数,$(document).ready()但稍后当情况发生变化时等等.

Mar*_*ein 50

你可以试试:

(window.powers = function(i) {
  /*Code here*/
  alert('test : ' + i);
})(2);
Run Code Online (Sandbox Code Playgroud)
<a href="#" onclick="powers(654)">Click</a>
Run Code Online (Sandbox Code Playgroud)

工作链接:http://jsfiddle.net/SqBp8/

它在加载时调用,我已将其添加到a anchor tag以更改参数和alert.

  • 聪明的解决方案!没有"窗口"也可以工作,但显然隐含的全局变量是邪恶的...... (4认同)

Mat*_*ard 32

如果你想要的只是访问自己体内的函数,你只需在function关键字后面指定一个名称:

> (function fac (n) {
    return (n === 0 ? 1 : n*fac(n-1));
  })(10)
3628800
Run Code Online (Sandbox Code Playgroud)

这是标准功能(参见ECMA-262,编辑5.1,第98页).

  • 它的功能非常优雅. (7认同)

gko*_*ger 10

这里的所有答案都接近你想要的,但有一些问题(将它添加到全局范围,而不是实际调用它等).这结合了这个页面上的几个例子(虽然不幸的是你需要记住arguments.callee):

var test = (function() {
  alert('hi');
  return arguments.callee;
})();
Run Code Online (Sandbox Code Playgroud)

之后,您可以调用它:

test();
Run Code Online (Sandbox Code Playgroud)

  • @Tivie但你可以命名匿名函数.`var test =(function fn(){alert('hi'); return fn;})();` (3认同)
  • 唯一的问题是arguments.callee是[已弃用](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments/callee)并在严格模式下在ES5上引发错误. (2认同)

twh*_*whb 6

如果您不关心返回值,则可以执行此操作.

var powers = function powers(i) {
    var product = i * i;
    console.log(i * i);
    if (product < 1e6) { powers(product) };
    return powers;
}(2);
Run Code Online (Sandbox Code Playgroud)