JavaScript - 自动执行匿名函数和回调 [英] JavaScript - self-executing anonymous functions and callback
问题描述
我可以使用具有自动执行功能的回调吗?
如果是,您看过任何示例吗?
Can I use callback with self-executing function?
If yes, have you seen any examples?
JavaScript自执行函数:
JavaScript self-executing function:
(function(){
//Do Stuff
})()
推荐答案
当然你可以 - 这是将变量封闭在某个函数中的常用方法,因此它们不会干扰全局变量(或来自单独的闭包)。
Of course you can - this is common way of enclosing your variables within some function so they do not interfere with global variables (or from separate closures).
一些例子:
(function(){
var counter = 0;
var step = function(){
counter++;
console.log(counter + ' Mississipi...');
};
setInterval(step, 1000);
})();
(function(){
var counter = 0;
var step = function(){
counter++;
console.log('3 seconds passed for a ' + counter + ' time');
};
setInterval(step, 3000);
})();
由于关闭,它们的变量不会干扰来自不同闭包的变量(不同的匿名)功能)。
Thanks to the closures, the variables from them are not interfering with the ones from different closure (different anonymous function).
这个jsfiddle 中的工作示例。
编辑:
您是否想要在此类函数的某些回调中执行代码,你可以这样写:
Is you want to execute the code from some callback in such function, you may write something like that:
var my_own_callback = function(data){
// some code for callback working on data passed
};
// ...
(function(callback){
var result; // future data sent to callback
// do whatever you need here
callback(result);
})(my_own_callback);
甚至是这样:
(function(callback){
var result; // data that will be sent to callback
// do whatever you need here
callback(result);
})(function(data){
// code for callback using data set to this callback
});
然而,这似乎相当疏忽,并且不必要地增加了代码的复杂性。
which, however, seems to be rather careless and unnecessarily increasing the complexity of your code.
这篇关于JavaScript - 自动执行匿名函数和回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!