JavaScript 作用域和闭包 [英] JavaScript scope and closure

查看:20
本文介绍了JavaScript 作用域和闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正想把头放在闭包上(某处有一个笑话),但我遇到了这个:

I'm trying to wrap my head around closures (there's a joke in there somewhere) and I ran across this:

(function () { /* do cool stuff */ })();

这是如何工作的?将函数放在括号中的目的是什么?为什么后面的括号是空的?

How does this work? What's the purpose of putting the function in parens? Why the empty parens afterwards?

推荐答案

这样做的重点是在很酷的东西中声明的任何变量都不会在全局命名空间中创建.javascript 中的任何函数都会创建这样的作用域.假设您有一些想要运行的 javascript.如果你这样做:

The point of this is that any variables declared in the cool stuff will not be created in global namespace. Any function in javascript will create such a scope. Suppose you have some javascript you want to run. If you do this:

var b = 1; 
// stuff using b

而其他一些代码使用 b,它将获得您剩余的价值.(或者,更糟糕的是,如果其他一些代码在您的代码运行之前设置了 b,然后尝试获取其旧值,那么您就会在此期间更改它.)

And some other code uses b, it will get your left over value. (Or, even worse, if some other code sets b before your code runs, then tries to get its old value later, you'd have changed it in the meantime.)

另一方面,如果你有这样的代码,它声明然后调用一个函数:

On the other hand, if you have this code, which declares and then calls the a function:

function a() { 
     var b = 1;
}

a();

稍后一些其他代码使用 b,它不会看到您的值,因为 b 是函数的本地值.当然,这样做的问题是您仍在创建全局名称 - 在这种情况下为a".所以,我们想要一个没有名字的函数——这就是为什么你得到你描述的代码.它声明了一个没有名字的函数,然后调用它.

And some other code later on uses b, it will not see your values, since b is local to the function. The problem with this, of course, is that you're still making a global name - "a", in this case. So, we want a function with no name - this is why you get the code you described. It declares a function with no name, and then calls it.

不幸的是,你不能只说:

Unfortunately, you can't just say:

function() { ... }()

因为这会被解析为函数声明statement,然后是语法错误.通过将函数声明包装在括号中,您得到一个函数表达式,然后可以调用该函数.您可以像任何其他函数表达式(如上面的 a)一样调用它,使用第二组括号.例如,如果该函数接受参数,您可以将它们传递到那里:

because this will be parsed as a function declaration statement, and then a syntax error. By wrapping the function declaration in parenthesis, you get a function expression, which can then be called. You call it like any other function expression (like a, above), using the second set of parens. For example, if the function took arguments, you'd pass them there:

(function(a) { ... })(1)

这篇关于JavaScript 作用域和闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆