什么是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);
发布了0 篇原创文章 · 获赞 75 · 访问量 56万+

猜你喜欢

转载自blog.csdn.net/w36680130/article/details/105450114
今日推荐