什麼是JavaScript中的(function(){})()構造?

本文翻譯自:What is the (function() { } )() construct in JavaScript?

I used to know what this meant, but I'm struggling now... 我曾經知道這意味着什麼,但是現在我正在努力...

Is this basically saying document.onload ? 這基本上是在說document.onload嗎?

(function () {

})();

#1樓

參考:https://stackoom.com/question/YWYD/什麼是JavaScript中的-function-構造


#2樓

Self-executing functions are typically used to encapsulate context and avoid name collusions. 自我執行功能通常用於封裝上下文並避免名稱衝突。 Any variable that you define inside the (function(){..})() are not global. 您在(function(){..})()內部定義的任何變量都不是全局變量。

The code 編碼

var same_name = 1;

var myVar = (function() {
    var same_name = 2;
    console.log(same_name);
})();

console.log(same_name);

produces this output: 產生以下輸出:

2
1

By using this syntax you avoid colliding with global variables declared elsewhere in your JavaScript code. 通過使用此語法,可以避免與JavaScript代碼中其他地方聲明的全局變量衝突。


#3樓

An immediately-invoked function expression (IIFE) immediately calls a function. 立即調用的函數表達式(IIFE)立即調用一個函數。 This simply means that the function is executed immediately after the completion of the definition. 這僅表示該函數在定義完成後立即執行。

Three more common wordings: 另外三種常用的措詞:

// Crockford's preference - parens on the inside
(function() {
  console.log('Welcome to the Internet. Please follow me.');
}());

//The OPs example, parentheses on the outside
(function() {
  console.log('Welcome to the Internet. Please follow me.');
})();

//Using the exclamation mark operator
//https://stackoverflow.com/a/5654929/1175496
!function() {
  console.log('Welcome to the Internet. Please follow me.');
}();

If there are no special requirements for its return value, then we can write: 如果對其返回值沒有特殊要求,那麼我們可以這樣寫:

!function(){}();  // => true
~function(){}(); // => -1
+function(){}(); // => NaN
-function(){}();  // => NaN

Alternatively, it can be: 或者,它可以是:

~(function(){})();
void function(){}();
true && function(){ /* code */ }();
15.0, function(){ /* code */ }();

You can even write: 您甚至可以寫:

new function(){ /* code */ }
31.new function(){ /* code */ }() //If no parameters, the last () is not required

#4樓

This is the self-invoking anonymous function. 這是自調用匿名功能。 It is executed while it is defined. 它在定義時執行。 Which means this function is defined and invokes itself immediate after the definition. 這意味着已定義此函數,並在定義後立即調用自身。

And the explanation of the syntax is: The function within the first () parenthesis is the function which has no name and by the next (); 語法的解釋是:first ()括號內的函數是沒有名稱的函數,next ();後面是該函數(); parenthesis you can understand that it is called at the time it is defined. 括號中,您可以理解它在定義時即被調用。 And you can pass any argument in this second () parenthesis which will be grabbed in the function which is in the first parenthesis. 您可以在第二個()括號中傳遞任何參數,該參數將在第一個括號中的函數中獲取。 See this example: 請參閱以下示例:

(function(obj){
    // Do something with this obj
})(object);

Here the 'object' you are passing will be accessible within the function by 'obj', as you are grabbing it in the function signature. 在這裏,您正在傳遞的“對象”將通過“ obj”在函數內訪問,就像您在函數簽名中抓住它一樣。


#5樓

I think the 2 sets of brackets makes it a bit confusing but I saw another usage in googles example, they used something similar, I hope this will help you understand better: 我認爲這兩組括號讓您感到有些困惑,但是我在Google的示例中看到了另一種用法,它們使用了類似的用法,希望這可以幫助您更好地理解:

var app = window.app || (window.app = {});
console.log(app);
console.log(window.app);

so if windows.app is not defined, then window.app = {} is immediately executed, so window.app is assigned with {} during the condition evaluation, so the result is both app and window.app now become {} , so console output is: 因此,如果未定義windows.app ,則將立即執行window.app = {} ,因此在條件評估期間將window.app分配爲{} ,因此結果是appwindow.app現在都變爲{} ,因此控制檯輸出爲:

Object {}
Object {}

#6樓

(function () {
})();

This is called IIFE (Immediately Invoked Function Expression). 這稱爲IIFE(立即調用函數表達式)。 One of the famous JavaScript design patterns, it is the heart and soul of the modern day Module pattern. 這是著名的JavaScript設計模式之一,它是現代Module模式的核心和靈魂。 As the name suggests it executes immediately after it is created. 顧名思義,它在創建後立即執行。 This pattern creates an isolated or private scope of execution. 這種模式創建了隔離的或私有的執行範圍。

JavaScript prior to ECMAScript 6 used lexical scoping, so IIFE was used for simulating block scoping. ECMAScript 6之前的JavaScript使用詞法作用域,因此IIFE用於模擬塊作用域。 (With ECMAScript 6 block scoping is possible with the introduction of the let and const keywords.) Reference for issue with lexical scoping (通過引入letconst關鍵字,可以使用ECMAScript 6進行塊作用域。) 詞彙作用域參考

Simulate block scoping with IIFE 使用IIFE模擬塊作用域

The performance benefit of using IIFE's is the ability to pass commonly used global objects like window , document , etc. as an argument by reducing the scope lookup. 使用IIFE的性能優勢是能夠通過減少範圍查找來將常用的全局對象(例如windowdocument等)作爲參數傳遞。 (Remember JavaScript looks for properties in local scope and way up the chain until global scope). (請記住,JavaScript在本地範圍內查找屬性,並在整個範圍內一直查找直到全局範圍)。 So accessing global objects in local scope reduces the lookup time like below. 因此,在本地範圍內訪問全局對象可以減少如下所示的查找時間。

(function (globalObj) {
//Access the globalObj
})(window);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章