javascript - 在定义函数的同时调用函数的快捷方式

Ani*_*ish 5 javascript function

在定义函数的同时调用它,我一直在使用:

var newfunc = function() {
    alert('hi');
};
newfunc();
Run Code Online (Sandbox Code Playgroud)

以下是将这两个组合的正确方法:

var newfunc = function() {
    alert('hi');
}();
Run Code Online (Sandbox Code Playgroud)

bbo*_*234 5

您希望这样做的原因可能有很多。我不确定你是什么,但让我介绍几个最喜欢的模式:

模式 1:单例。该函数被执行,然后成为供代码的其他组件使用的单例对象。

var singletonObject = new function() {

    // example private variables and functions
    var variable1 = {};
    var variable2 = {};
    var privateFunction = function() { 
    };

    // example public functions
    this.getData = function() { 
        return privateFunction(variable1, variable2);
    };

    // example initialisation code that will only run once
    variable1.isInitialised = true;
};
Run Code Online (Sandbox Code Playgroud)

模式#2:自执行匿名函数......因为很多原因很方便!

// Declare an anonymous function body. 
// Wrap it in parenthesis to make it an "expression.
// Execute it by adding "();"
(function(){})();
Run Code Online (Sandbox Code Playgroud)

这是一个示例,它也为您的对象创建了一个命名空间。我使用“NS”作为示例命名空间:

// declare the anonymous function, this time passing in some parameters
(function($, NS) {

    // do whatever you like here

   // execute the function, passing in the required parameters. 
   // note that the "NS" namespace is created if it doesn't already exist
})(jQuery, (window.NS = window.NS || {}));
Run Code Online (Sandbox Code Playgroud)

您还可以使用 .call 或 .apply 代替通常的括号来设置自执行函数的上下文,如下所示:

(function($){
    // 'this' now refers to the window.NS object

}).call(window.NS = window.NS || {}, jQuery);
Run Code Online (Sandbox Code Playgroud)

或者

(function($){
    // 'this' now refers to the window.NS object

}).apply(window.NS = window.NS || {}, [jQuery]);
Run Code Online (Sandbox Code Playgroud)


Que*_*tin 4

不会。您的第二个示例将立即调用匿名函数并将其返回值分配给newfunc。

adamse 描述了一种似乎有效的方法。我仍然会避免这种方法,因为两步过程更容易阅读,因此更容易维护。