正常函数与自执行匿名函数有什么区别?在哪些情况下应该使用自执行匿名函数?我真的不理解它们之间的区别。如何使用自执行匿名函数?
function() { ... };
你所做的就是定义它,目前它还没有被使用。如果你愿意,可以将其分配给一个变量并在以后调用它,或将变量作为参数传递给另一个函数。
自执行匿名函数是JavaScript中用于命名空间的极其有用的模式组件。我更喜欢使用更准确的名称——立即执行函数表达式(IIFE)。要理解这种模式,建议您阅读有关JavaScript闭包的内容:JavaScript闭包如何工作?
(function(namespace, $, undefined){ //undefined is specified here as it can be overwritten in javascript. This ensures we have a true undefined value within our namespace. Make sure not to pass in any argument for this.
var text = "hello world"; // private member
var namespace.text = "hellow world"; //public member
}(window.namespace = window.namespace || {}, jQuery)); //This section calls this function immediately and creates a closure. We pass in the window.namespace argument to give us access to all public member of the namespace.
我确定SIAF有许多用途!但主要用于命名空间和隐私!
关于隐私:
var normalkey=89000333;
var privateKey= (function(param){
var secretkey = 123411;
//it is private , nothing outside this function will know of it
var newkey=param+secretkey ;
return newkey
})(normalkey); //passing normalkey as param
var fruits= (function() {
return {
name: ["apple", "orange"];
color: [{"red","green"},"orange"]
}
})();
不需要在全局命名空间中声明fruitname、fruitcolor等内容,您可以从“fruits”获取所有内容。
为了自我调用的目的
$(function(){}); //seem familiar? -jquery