調用在它的定義相同時間的函數,同時調用一個函數,我一直在使用:的JavaScript - 快捷方式,它被定義
var newfunc = function() {
alert('hi');
};
newfunc();
是結合這2以下的正確方法:
var newfunc = function() {
alert('hi');
}();
調用在它的定義相同時間的函數,同時調用一個函數,我一直在使用:的JavaScript - 快捷方式,它被定義
var newfunc = function() {
alert('hi');
};
newfunc();
是結合這2以下的正確方法:
var newfunc = function() {
alert('hi');
}();
號你的第二個例子將立即撥打匿名函數和它的返回值賦給newfunc
。
adamse描述了一種似乎可行的方法。我仍然避免使用這種方法,因爲這兩步過程更容易閱讀,因此更容易維護。
var newfunc = function f() {
alert("hi!");
return f;
}();
命名函數表達式允許函數以遞歸方式調用自身,或者在這種情況下返回自身。這個函數總是會返回自己,但是,這可能是一個煩惱。
的問題,這是Internet Explorer的JScript引擎的行爲不同的其他瀏覽器。在IE中,這段代碼在外部範圍中創建了兩個變量(和兩個函數!) - * newfunc *和* f *。在其他瀏覽器(和ECMAScript規範)中,* newfunc *在外部作用域中創建,* f *僅在內部作用域中可用。此代碼在全局範圍內使用時尤其具有潛在危險。 – 2010-08-22 09:10:05
關於這個主題的進一步閱讀:http://yura.thinkweb2.com/named-function-expressions/#jscript-bugs – 2010-08-22 09:12:17
@Andy:我知道IE瀏覽器顯示奇怪的行爲與命名的函數表達式,但從你的鏈接似乎是一場噩夢。 – adamse 2010-08-22 15:27:25
如果我正確理解你的問題,試試這個:
(f = function (msg) {
msg = msg ? msg : 'default value';
alert(msg); }
)();
f('I\'m not the default value!');
你會得到兩個警報,第一個會說「默認值」,第二個會說:「我不是。默認值可以在jsBin看到它在行動點擊「預覽」,使其運行
,你可以這樣做:。
o = {};
o.newfunc = (function() {
function f() {
alert('hi');
}
f();
return {
f : f
};
}
)();
然後調用函數,如:
o.newfunc.f();
也將呈現一條警告消息
我不認爲這段代碼實現了在一行中獲得賦值和函數調用的目標。 – 2012-10-26 08:39:10
有可能是你希望這樣做有許多原因。我不知道你的是什麼,但讓我介紹一些最喜歡的模式:
模式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:自執行的匿名函數...得心應手SOOO很多原因!
// 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設置一個自動執行功能的情況下還是。適用而不是通常的括號,就像這樣:
(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]);
我知道「單身人士」並不是單純的單身人士......它可以在代碼中的另一個時間「新增」......這只是我在創建旨在用作單身人士的對象時使用的編碼風格。 – bboyle1234 2013-05-31 04:17:54
http://www.jibbering.com/faq/notes/closures/ – 2010-08-22 08:41:36