繁体   English   中英

我可以稍后再调用一个匿名函数吗

[英]Can i call an anonymous function later on

我正在使用JavaScript开发函数,我想知道以后是否可以调用匿名函数:

code
more code

(function() {
alert('Hello World!');
})();
more code
(function() {
alert('Goodbye World!');
})();

//call to the first anonymous function
//call to the first anonymous function 

可以调用匿名函数吗? 我想可能会有一个包含所有函数的数组?

由于函数是“一等公民”,因此您可以将它们分配给变量,或者将它们放入数组/对象中,就像其他变量一样,无论它们是否匿名。

因此,您必须将匿名函数分配给变量(或将其放入数组),以便日后使用某种方式引用它。

此外,您不会立即执行它,而是稍后执行。

var anon1 = (function(){
    alert("anon1");
}); // <-- no () so it doesn't execute now.

// code code

anon1(); // <-- execute now

// ----- or -------
var myFuncs = [];

myFuncs.push( (function(){
    alert("in myFuncs");
}) ); // <-- not executing it here.

// code code

myFuncs[0](); // <-- execute now

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM