简体   繁体   English

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

[英]Can i call an anonymous function later on

I was working on a function in JavaScript and i wondered if i could call a 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 

Is it possible to call anonymous functions? 可以调用匿名函数吗? I imagine there could be an array containing all functions? 我想可能会有一个包含所有函数的数组?

Since functions are "first class citizens" you can assign them to variables, or put them into arrays/objects whatever just like any other var, whether they're anonymous or not. 由于函数是“一等公民”,因此您可以将它们分配给变量,或者将它们放入数组/对象中,就像其他变量一样,无论它们是否匿名。

So you'll have to assign the anonymous function to a variable (or put it into an array) in order to have some kind of means to reference it later on. 因此,您必须将匿名函数分配给变量(或将其放入数组),以便日后使用某种方式引用它。

Furthermore, you don't execute it immediately, rather you execute it at a later time. 此外,您不会立即执行它,而是稍后执行。

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.

相关问题 如何将匿名函数初始化为变量并在以后使用? - How can I initial an anonymous function into a variable and use it later? 如何在javascript匿名函数中调用类释放函数 - How can I call the class slibing function in javascript anonymous function 如何在JavaScript中从内部调用匿名函数? - How can I call an anonymous function from inside itself in JavaScript? 我可以通过触发一些东西在jQuery中调用这个匿名函数吗? - Can I call this anonymous function in jQuery by triggering something? 如何在该匿名javascript中调用该函数? (TinyMce示例) - How can i call that function inside that anonymous javascript? (TinyMce example) 如何在JavaScript中使用参数调用匿名函数(存储在字符串中)? - How can I call an anonymous function (stored in string) with an argument in JavaScript? 如何在不使用Eval的情况下调用匿名函数? - How can I call anonymous function without using Eval? 为什么不能将函数调用(而不是函数引用或匿名函数)传递给setTimeout()? - Why can I not pass a function call (rather than a function reference or an anonymous function) to setTimeout()? 如果我想,如何稍后调用JS自执行函数? - how can I call a JS self-executing function later if I want? 我可以在此示例中立即调用函数,而不用匿名函数将其包装吗? - Can I call my function in this example immediately instead of wrap it by anonymous function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM