我继承了一个应用程序,到处都可以看到这个JavaScript结构。
那样创建它的原因是什么。我知道这是一个匿名函数,并且PaymentOffersOverview传递给了它。

var PaymentOffersOverview = PaymentOffersOverview || {};

(function(PaymentOffersOverview) {
    var App = {};

    App.Settings = {
        Id: some Id value
        // Some Code
    };

    App.ShowLoader = function (message) {
            // Some Code
        };

    PaymentOffersOverview.App = App;
})(PaymentOffersOverview);

但是我没有得到的是最后一行。 })(PaymentOffersOverview);为什么会再次传入?
// Then the code can be used as follow

alert(PaymentOffersOverview.App.Settings.Id);

Fiddle

最佳答案

它不会再次传递。在最后一行,闭包将自动调用PaymentOffersOverview。如果未通过,则闭包内的PaymentOffersOverview将为undefined

// definition of local variable
var PaymentOffersOverview = PaymentOffersOverview || {};

(function(param) {
    // now we are in the context of the closure where param refers to
    // PaymentOffersOverview, yet PaymentOffersOverview is not defined
    // within this scope. It is param.
    // You can use any name here, using the same is just for convinience.
    var App = {};

    App.Settings = {
        Id: some Id value
        // Some Code
    };

    App.ShowLoader = function (message) {
            // Some Code
        };

    param.App = App;
})(PaymentOffersOverview); // passing of the variable

10-02 03:37