普通函数和自调用匿名函数有什么区别?在什么情况下我应该使用自调用匿名函数?我真的不明白他们之间的区别。我如何使用 SIAF?
最佳答案
Javascript 中的函数是一等公民,可以像对象一样传递。当你像这样定义一个函数时:
function() { ... };
这就是你所做的一切。定义它。目前没有使用它。您可以将它分配给一个变量,如果您愿意,稍后可以调用它,或者将该变量作为参数传递给另一个函数。
自调用匿名函数是一个非常有用的模式组件,用于 Javascript 中的命名空间。我更喜欢使用更准确的名称立即调用函数表达式 (IIFE)。要理解这种模式,我建议您阅读 javascript 中的闭包:How do JavaScript closures work?
(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.
这为您提供了一个命名空间以避免全局范围污染,并允许您定义私有(private)函数和成员。
您可以在此处找到更多信息:http://benalman.com/news/2010/11/immediately-invoked-function-expression/
关于javascript - 函数和自调用匿名函数之间的 jQuery 区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18913486/