这个javascript如何自我执行功能/结构工作

时间:2015-05-25 11:59:46

标签: javascript

我继承了一个应用程序,我到处都看到了这个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

1 个答案:

答案 0 :(得分:0)

它不会再次传入。在最后一行,闭包得到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