2

JavaScript 関数式を呼び出すときに、次のようなさまざまなパターンを見てきました。

パターン #1

var global = function () {
    return this;
}();

パターン #2

var global = (function () {
   return this;
}());

パターン #3

var global = (function () {
    return this;
})();

私のテストでは、すべてが機能しているようです (少なくとも最新のブラウザでは)。私の「好み」では、パターン #3 の方が優れています。これは #1 よりも明示的であり、#2 とは対照的に、実際に呼び出す前に関数を返すためです。

しかし、好ましいものまたはより正しいものがあるかどうか、私はさまよっていました...

4

3 に答える 3

2

So, the initial problem is that the code below:

function () {

}();

Raises an exception. That's because the JS parser is not able to automatically determined if it's a function declaration or a function expression. All the patterns you described are used to explicitly tell to JS "hey dude, that's an expression". But in you specific case you don't have that problem, because if you have a variable in front, JS is perfectly able to understand that is an expression, not a declaration,and it doesn't raise any syntax error.

In that specific case there is no need to any "hack", you can simply have:

var _global = function () {

}();

And that's it. The question now is: which "hack" use when you need to have a immediate function invocation without any variable? All the pattern you described are okay, Crockford tends to prefer this one:

(function(){

}());

That's makes sense to me, at least because you have a full isolated block, compared to:

(function(){

})();

However, if you join your code with other scripts, or you have previous code, you could end up with some problem if they don't use semicolon at the end:

a = b + c
(function() {

}());

In this scenario JS consider c a function's call:

a = b + c(function() { }());

To avoid that, developers usually add a semicolon in front, just to be safe:

;(function() {

}());

I personally prefer some operator instead, like the bang (!):

!function () {

}();

With that you don't have the issues you have using parenthesis. Less characters, and gives to me a sense of "execution". But, like the other approach, it's an hack and it's a matter of personal taste. For instance Crockford dislike A LOT that bang stuff.

于 2012-06-03T16:06:17.503 に答える
0

それらはすべて正常に機能し、それらのいずれかを使用できます。Crockfordが推奨するパターンはパターン #2 です。

var global = (function () {
   return this;
}());

個人的には、パターン #3 は従うのが簡単なので、扱いやすいと思います。

var global = (function () {
    return this;
})();

!ところで、、、+などの文字を使用する他のパターン/省略形もあります。

! function(){
  return this;
}();
于 2012-06-03T15:31:34.553 に答える
0

関数をオブジェクトのプロパティとして定義する場合のパターン 1 を好みます。これは、構文が非常に冗長になるためです。パターン #1 に従うのは簡単です。関数を定義してから呼び出します。パターン 3 は同じことを行いますが、追加のセットが()続きます。私の意見では、この冗長性は生産性を犠牲にします。

あなたが言ったように、それらはすべて正しいですが、「オッカムのかみそり」を覚えておくことが重要だと思います=>すべてが等しい場合、より単純な説明(式)はより複雑なものよりも優れています.

于 2012-06-03T15:32:59.140 に答える