在定义的同时调用一个函数,我一直在使用:
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/