60

Possible Duplicate:
How do JavaScript closures work?

I was playing around with the Google Closure Compiler, putting in random code to see what it would do.

It rewrote one of my functions to look something like this:

(function(msg) { console.log(msg); })("Hello World!");​​​​​​​

Where it appears that "Hello World" is the argument passed as msg to the anonymous function preceding it. I was looking at it for a moment, and had thought that I had seen something similar in jQuery plugins that look something like:

(function( $ ) {
  ...
})(jQuery); 

Which now makes more sense to me, in the scope of conflicts with $. But what is the primary reason or purpose for passing arguments into an anonymous function like this? Why wouldn't you simply define the arguments as variables within the function? Is there any performance or flexibility advantage to writing functions like this?

4

3 に答える 3

20

There is one significant difference connected also to scope. The following code:

(function(msg) { console.log(msg); })("Hello World!");​​​​​​​

is in some circumstances cleaner in terms of namespace pollution than this:

var msg = "Hello World!";
console.log(msg);

because the second code leaves variable after it is no longer needed, but may interfere with other parts of the code.

This is especially important when you execute the mentioned code outside any other function: in such case msg variable would be available everywhere on the page, as global variable.

于 2012-10-02T21:27:39.493 に答える
0

基本的に、コードをこれでラップしたままにしておくことをお勧めし(function(){/*code*/}());ます。つまり、変数が他の人の変数と衝突しないようにするためです。

クロージャコンパイラが得ている主なことは、5文字を保存することだと思います:var =

于 2012-10-02T21:34:50.097 に答える
0

それは文脈に少し依存します。コンパイラが関数をまったくインライン化しようとしない条件がいくつかあります(たとえば、スコープ関数に「eval」が含まれている場合)。これがグローバルスコープであり、ADVANCEDモードで実行している場合は、コンパイラが関数のインライン化の試行を停止した後にインライン化の機会が表示されただけです(または、インライン化コードにバグがあり、機会を逃しました)。ADVANCEDモードでコンパイラーを介してサンプル出力を実行すると、次のようになります。

console.log("Hello World!");
于 2012-10-03T01:02:57.950 に答える