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

标签 javascript function

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

var newfunc = function() {
    alert('hi');
};
newfunc();

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

var newfunc = function() {
    alert('hi');
}();

最佳答案

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

模式 #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;
};

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

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

这里还有一个示例,它还为您的对象创建了一个命名空间。 我使用“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 || {}));

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

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

}).call(window.NS = window.NS || {}, jQuery);

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

}).apply(window.NS = window.NS || {}, [jQuery]);

关于javascript - 在定义函数的同时调用函数的快捷方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3540760/

相关文章:

javascript - 如何让我的整个弹出窗口背景颜色改变

javascript - 为什么 api 调用在 gh-pages 上不起作用

javascript - 编写一个接受正整数 N 并返回 N 的函数

c# - 在 ASP.NET MVC 中执行 ListView 的最佳方法?

javascript - 当第一个选项卡处于事件状态时,第二个选项卡不起作用

javascript - 在 JavaScript 中合并两个对象

python - 基于状态与传递参数

html - 你们有什么函数或工具可以将简单的 html 转换为我喜欢的特殊代码吗?

php - JavaScript 在函数之间传递变量并处理它们

wordpress - apply_filters(...) 在 WordPress 中实际上做了什么?