1つ目は、即時呼び出し関数の戻り値です。2つ目は関数です。それは本質的にこれらの違いが何であるかに帰着します:
var f = (function() { return 0; })();
var f = function() { return 0; };
最初の関数がすぐに呼び出されるため、変数に値0が与えられますf
。1つ目f
は関数ではありません。ただし、f
値を取得するために2番目に呼び出す必要があります。
f(); // 0
したがって、あなたの例では、最初BW.Timer
はオブジェクトリテラル自体であり、2番目はオブジェクトリテラルを返す関数です。オブジェクトに到達するには、関数を呼び出す必要があります。
BW.Timer().Add(x);
なぜ最初のものを使うのですか?
a = (function() { return {}; })()
なぜの代わりにのような構文を使用するのかと自問するかもしれませんがa = {}
、それには十分な理由があります。IIFE(即時呼び出し関数式)は、通常の関数とは異なり、静的変数(単一のインスタンスを通じて値を維持する変数)のエミュレーションを可能にします。例えば:
var module = (function() {
var x = 0;
return { get: function() { return x },
set: function(n) { x = n }
};
})();
The above a text-book example of the Module Pattern. Since the function is called right away, the variable x
is instantiated and the return value (the object) is given to module
. There's no way we can get to x
other than by using the get
and set
methods provided for us. Therefore, x
is static, meaning its variable won't be overridden each time you use module
.
module.set(5);
module.get(); // 5
On the other hand, let's see an example where module
is declared as a function instead:
// assume module was made as a function
module().set(5);
module().get(); // 0
When we call module()
the x
variable is overridden each time. So we're effectively using different instances of module
and x
each time we call module
.