7

以下は、BW.Timerを定義する2つの方法です。誰かが違いを教えてもらえますか?最初のものが有効かどうかはわかりませんが、有効な場合、myfunc=(function(){}())構文の使用の違いは何ですか?

BW.Timer = (function () {
    return {
        Add: function (o) {
            alert(o);
        },
        Remove: function (o) {
            alert(o);
        }
    };
} ());

と...

BW.Timer = function () {
    return {
        Add: function (o) {
            alert(o);
        },
        Remove: function (o) {
            alert(o);
        }
    };
};
4

3 に答える 3

9

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.

于 2012-12-04T20:00:36.673 に答える
3

The difference is rather large.

In the first case, BW.Timer is executed when it is first encountered, and that is the static version assigned to BW.Timer. In that instance, BW.Timer.Add(1) may be used. Each call to BW.Timer will be the same object.

In the second case, BW.Timer is not executed when first encountered, and instead is a function referece which must be invoked BW.Timer(). For Add to be used, this must be the case BW.Timer().Add(1). Also, you can issue var timer = new BM.Timer();. Each instance of BW.Timer() will be unique here.

于 2012-12-04T20:02:06.013 に答える
2

In the first example BW.Timer references an object that the self-executing function returns, while in the second example it references a function object, in other words it's a function that can be executed BW.Timer().

于 2012-12-04T20:01:48.083 に答える