常见这样一种函数:(function() {//函数体}() );
最近查找第三方库的看别人的封装模块代码常常看见这样一个写法,最初的理解就是定义了一个定义后即执行的函数而已,实现了一个局部的封装,方便其他JS框架的调用,看了《JavaSctipt权威指南》8.6 Function As Namespae后又有了一点点深入的理解,简单说说看。先看看书里的说明,这里摘要着说,其实这章内容不多,可以去通读一下,毕竟这本书还是比较系统和权威的。
variables declared within a function are visible throughout the function (including within nested functions) but do not exist outside of the function.
【声明在一个函数内的变量值在函数内可见(可用),函数外就不可见了(不可用)】
Variables declared outside of a function are global variables and are visible throughout your JavaScript program.【声明在函数外面的变量是全局变量,在整个JavaScript程序均可见(可用)】
JavaScript does not define any way to declare variables that are hidden within a single block of code
【JavaScript没有把变量隐藏在一个代码块中使用的方式】
为避免定义的外部模块中的全局变量污染(polluting)整个程序的全局作用域,于是JavaScript提供了函数来定义一个作用域作为命名空间(函数的命名空间)原始方式:将变量放在函数中就是局部变量了
function mymodule() {// Module code goes here.// Any variables used by the module are local to this function// instead of cluttering up the global namespace.}mymodule(); // But don't forget to invoke the function!更简洁的方式:(function() { // mymodule function rewritten as an unnamed expression// Module code goes here.}()); // end the function literal and invoke it now.
书中这样说:
This technique of defining and invoking a function in a single expression is used frequently enough that it has become idiomatic.
【这种使用一个单一的表达式定义和调用函数的技术已经是非常广泛的常见方法】
注意:最外面的括号不能省略,不然JS解释器会先解释function关键字,把这段code当成了函数定义,不能够自执行了。这里有一个和闭包(Closures)结合的例子来加深理解:
var baz;(function(){var foo = 10;var bar = 2;baz = function(){return foo*bar;};})(); baz (); /// 返回20 //来源《JavaScript设计模式》
顺便一提,上面红色的括号内是可以传入参数的,
如下面例子:var baz = (function(foo,bar){return foo*bar;})(2,10); /// baz结果是20