Nice programing

JavaScript에서 (function () {}) () 구조는 무엇입니까?

nicepro 2020. 9. 29. 18:42
반응형

JavaScript에서 (function () {}) () 구조는 무엇입니까?


이게 무슨 뜻인지 알고 있었는데 지금은 힘들어 ...

이것은 기본적으로 말하는 것 document.onload입니까?

(function () {

})();

그것은이다 즉시-호출 기능 발현 , 또는 인생 에 대한 짧은. 생성 된 직후에 실행됩니다.

이벤트 (예 :)에 대한 이벤트 핸들러와는 관련이 없습니다 document.onload.
첫 번째 괄호 쌍 안에있는 부분을 고려하십시오. .... 정규 함수 표현식입니다. 그런 다음 마지막 쌍을보십시오 . 이것은 일반적으로 함수를 호출하기 위해 표현식에 추가됩니다. 이 경우 우리의 이전 표현입니다.(function(){})();(function(){})();

이 패턴은 IIFE 내부에서 사용되는 모든 변수 (다른 일반 함수 에서와 마찬가지로 )가 해당 범위 외부에서 보이지 않기 때문에 전역 네임 스페이스를 오염시키지 않으려 고 할 때 자주 사용됩니다 .
이것이 window.onload종종 다음과 같이 사용되기 때문에이 구성을 이벤트 핸들러와 혼동 한 이유입니다 .

(function(){
    // all your code here
    var foo = function() {};
    window.onload = foo;
    // ...
})();
// foo is unreachable here (it’s undefined)

Guffa가 제안한 수정 사항 :

함수는 구문 분석 된 후가 아니라 생성 된 직후에 실행됩니다. 전체 스크립트 블록은 코드가 실행되기 전에 구문 분석됩니다. 또한 구문 분석 코드는 자동으로 실행된다는 것을 의미하지 않습니다. 예를 들어 IIFE가 함수 내부에 있으면 함수가 호출 될 때까지 실행되지 않습니다.

업데이트 이것은 꽤 인기있는 주제이기 때문에 IIFE는 ES6의 화살표 기능으로 도 작성할 수 있다는 것을 언급 할 가치가 있습니다 ( Gajus주석에서 지적한 것처럼 ).

((foo) => foo)('foo value')

생성 된 직후에 실행되는 익명의 함수입니다.

마치 변수에 할당하고 변수없이 바로 사용하는 것과 같습니다.

var f = function () {
};
f();

jQuery에는 생각할 수있는 유사한 구조가 있습니다.

$(function(){
});

ready이벤트 바인딩의 약식입니다 .

$(document).ready(function(){
});

즉시 호출 된 함수 식 (IIFE)은 즉시 함수를 호출합니다. 이것은 단순히 정의가 완료된 직후에 함수가 실행됨을 의미합니다.

세 가지 더 일반적인 표현 :

// 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.');
}();

반환 값에 대한 특별한 요구 사항이 없으면 다음과 같이 작성할 수 있습니다.

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

또는 다음과 같을 수 있습니다.

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

다음과 같이 작성할 수도 있습니다.

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

익명 함수를 선언 한 다음 호출합니다.

(function (local_arg) {
   // anonymous function
   console.log(local_arg);
})(arg);

그것은 즉시 실행을 의미합니다.

그래서 만약 내가 :

var val = (function(){
     var a = 0;  // in the scope of this function
     return function(x){
         a += x;
         return a;
     };
})();

alert(val(10)); //10
alert(val(11)); //21

바이올린 : http://jsfiddle.net/maniator/LqvpQ/


두 번째 예 :

var val = (function(){
     return 13 + 5;
})();

alert(val); //18

이 구조는 즉시 실행되는 즉시 호출 된 함수 표현식 (IIFE) 이라고 합니다. 인터프리터가 해당 기능에 도달하면 자동으로 호출되는 함수로 생각하십시오.

가장 일반적인 사용 사례 :

가장 일반적인 사용 사례 중 하나는를 통해 만든 변수의 범위를 제한하는 것 var입니다. 를 통해 생성 된 변수 var는 함수로 제한된 범위 가지므로이 구성 (특정 코드를 둘러싼 함수 래퍼)은 변수 범위가 해당 함수에서 누출되지 않도록합니다.

다음 예에서 count는 즉시 호출 된 함수 외부에서 사용할 수 없습니다. 즉, 범위가 함수에서 count누출되지 않습니다. 당신은을 받아야 Reference Error어쨌든 바로 호출 기능을 외부에서 액세스하려고한다.

(function () { 
    var count = 10;
})();
console.log(count);  // Reference Error: count is not defined

ES6 대안 (권장)

ES6, 우리는 지금 통해 생성 된 변수 수 letconst. 둘 다 블록 범위입니다 ( var함수 범위 와 달리 ).

따라서 위에서 언급 한 사용 사례에 대해 복잡한 IIFE 구성을 사용하는 대신 변수의 범위가 원하는 블록에서 누출되지 않도록 훨씬 더 간단한 코드를 작성할 수 있습니다.

{ 
    let count = 10;
};
console.log(count);  // Reference Error: count is not defined

이 예에서는 코드 블록으로 제한 let되는 count변수 를 정의 count하고 중괄호를 사용하여 생성했습니다 {...}.

나는 그것을 Curly Jail.


(function () {
})();

이를 IIFE (Immediately Invoked Function Expression)라고합니다. 유명한 JavaScript 디자인 패턴 중 하나 인이 패턴은 현대 모듈 패턴의 핵심입니다. 이름에서 알 수 있듯이 생성 된 직후에 실행됩니다. 이 패턴은 격리되거나 비공개 실행 범위를 만듭니다.

ECMAScript 6 이전의 JavaScript는 어휘 범위 지정을 사용 했으므로 IIFE는 블록 범위 시뮬레이션에 사용되었습니다. (ECMAScript 6을 사용하면 letconst키워드 의 도입으로 블록 범위 지정이 가능 합니다.) 어휘 범위 지정 문제에 대한 참조

IIFE로 블록 범위 지정 시뮬레이션

인생의 사용의 성능 이점은 같은 일반적으로 사용되는 전역 개체 전달하는 능력이다 window, document범위 조회를 줄여 인수로 등. (JavaScript는 로컬 범위에서 속성을 찾고 전역 범위까지 체인을 따라가는 것을 기억하십시오). 따라서 로컬 범위의 전역 개체에 액세스하면 아래와 같이 조회 시간이 단축됩니다.

(function (globalObj) {
//Access the globalObj
})(window);

아니요,이 구성은 이름 지정 범위를 만듭니다. 당신이 그것을 부분적으로 부 수면 당신은 외부

(...)();

이것이 함수 호출입니다. 괄호 안에 다음이 있습니다.

function() {}

그것은 익명의 기능입니다. 구문 내에서 var 로 선언 된 모든 것은 동일한 구문 내에서만 표시되며 전역 네임 스페이스를 오염시키지 않습니다.


이것은 Javascript에서 즉시 호출되는 함수 표현식입니다.

JS에서 IIFE를 이해하려면 다음과 같이 분해 해 보겠습니다.

  1. 표현식 : 값을 반환하는 것
    예 : 크롬 콘솔에서 다음을 시도해보세요. 이것들은 JS의 표현입니다.
a = 10 
output = 10 
(1+3) 
output = 4
  1. 함수 표현식 :
    예 :
// Function Expression 
var greet = function(name){
   return 'Namaste' + ' ' + name;
}

greet('Santosh');

함수 표현식 작동 방식 :
-JS 엔진이 처음 실행될 때 (Execution Context-Create Phase),이 함수 (= 위의 오른쪽)는 실행되거나 메모리에 저장되지 않습니다. 변수 'greet'는 JS 엔진에 의해 '정의되지 않은'값으로 할당됩니다.
-실행 중 (Execution Context-Execute 단계), funtion 객체는 즉석에서 생성되고 ( 아직 실행되지 않음 ) 'greet'변수에 할당되며 'greet ('somename ')'을 사용하여 호출 할 수 있습니다.

3. 즉시 호출 된 기능 표현 :

예:

// IIFE
var greeting = function(name) {
    return 'Namaste' + ' ' + name;
}('Santosh')

console.log(greeting)  // Namaste Santosh. 

IIFE의 작동 원리 :
-함수 선언 바로 뒤에 '()'가 있습니다. 모든 기능 개체에는 호출 가능한 'CODE'속성이 연결되어 있습니다. 그리고 '()'중괄호를 사용하여 호출 (또는 호출) 할 수 있습니다.
-그래서 여기에서 실행하는 동안 (Execution Context-Execute Phase) 함수 객체가 생성되고 동시에 실행됩니다 .-이제는 funtion 객체를 갖는 대신 greeting 변수가 반환 값 (문자열)을 갖습니다.

JS에서 IIFE의 일반적인 사용 사례 :

다음 IIFE 패턴은 매우 일반적으로 사용됩니다.

// IIFE 
// Spelling of Function was not correct , result into error
(function (name) {
   var greeting = 'Namaste';
   console.log(greeting + ' ' + name);
})('Santosh');
  • 우리는 여기서 두 가지를하고 있습니다. a) 함수 표현식을 중괄호 ()로 묶습니다. 이것은 구문 파서에게 () 안에있는 것이 표현식 (이 경우 함수 표현식)이고 유효한 코드임을 알려줍니다.
    b)이 함수는 끝에 ()를 사용하여 동시에 호출합니다.

따라서이 함수는 동시에 생성되고 실행됩니다 (IIFE).

IIFE의 중요한 사용 사례 :

IIFE는 코드를 안전하게 유지합니다.
-IIFE는 함수로서 자체 실행 컨텍스트를 가지고 있습니다. 즉, 내부에서 생성 된 모든 변수는이 함수에 로컬이며 전역 실행 컨텍스트와 공유되지 않습니다.

iife.js (아래 참조)와 함께 내 응용 프로그램에 사용 된 다른 JS 파일 (test1.js)이 있다고 가정합니다.

// test1.js

var greeting = 'Hello';

// iife.js
// Spelling of Function was not correct , result into error
(function (name) { 
   var greeting = 'Namaste';
   console.log(greeting + ' ' + name);
})('Santosh');

console.log(greeting)   // No collision happens here. It prints 'Hello'.

따라서 IIFE 는 의도하지 않게 전역 개체와 충돌하지 않는 안전한 코드작성 하는 데 도움이됩니다 .


이것은 자체 호출 익명 함수 입니다.

자체 호출 기능에 대한 W3Schools 설명을 확인하십시오 .

함수 표현식은 "자체 호출"로 만들 수 있습니다.

자체 호출 표현식은 호출되지 않고 자동으로 호출 (시작)됩니다.

표현식 뒤에 ()가 오면 함수 표현식이 자동으로 실행됩니다.

함수 선언을 자체 호출 할 수 없습니다.


이것은 자체 호출 익명 함수입니다. 정의 된 동안 실행됩니다. 즉,이 함수가 정의되고 정의 직후에 자체적으로 호출됩니다.

그리고 구문에 대한 설명은 다음과 같습니다. 첫 번째 ()괄호 안의 함수는 이름이없는 함수이며 다음 ();괄호로 정의 할 때 호출되는 것을 이해할 수 있습니다. 그리고 ()첫 번째 괄호에있는 함수에서 잡을 이 두 번째 괄호의 모든 인수를 전달할 수 있습니다 . 이 예를 참조하십시오.

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

여기서 전달하는 '객체'는 함수 서명에서 잡는 것처럼 'obj'에 의해 함수 내에서 액세스 할 수 있습니다.


여기에서 시작하십시오.

var b = 'bee';
console.log(b);  // global

함수에 넣으면 더 이상 글로벌아닙니다 .

function a() {
  var b = 'bee';
  console.log(b);
}
a();
console.log(b);  // ReferenceError: b is not defined -- *as desired*

즉시 함수를 호출하십시오-죄송합니다 :

function a() {
  var b = 'bee';
  console.log(b);
}();             // SyntaxError: Expected () to start arrow function, but got ';' instead of '=>'

구문 오류를 방지하려면 괄호를 사용하십시오.

(function a() {
  var b = 'bee';
  console.log(b);
})(); // OK now

함수 이름은 생략 할 수 있습니다.

(function () {    // no name required
  var b = 'bee';
  console.log(b);
})();

그것보다 더 복잡 할 필요는 없습니다.


자체 실행 익명 기능. 생성되는 즉시 실행됩니다.

이것이 유용한 한 가지 짧고 더미 예제는 다음과 같습니다.

function prepareList(el){
  var list = (function(){
    var l = []; 
    for(var i = 0; i < 9; i++){
     l.push(i);
    }
    return l;
  })();

  return function (el){
    for(var i = 0, l = list.length; i < l; i++){
      if(list[i] == el) return list[i];
    }
    return null;
  }; 
} 

var search = prepareList();
search(2);
search(3);

따라서 매번 목록을 만드는 대신 한 번만 만듭니다 (더 적은 오버 헤드).


자체 실행 함수는 일반적으로 컨텍스트를 캡슐화하고 이름 공모를 방지하는 데 사용됩니다. (function () {..}) () 내부에 정의한 변수는 전역이 아닙니다.

코드

var same_name = 1;

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

console.log(same_name);

다음 출력을 생성합니다.

2
1

이 구문을 사용하면 JavaScript 코드의 다른 곳에서 선언 된 전역 변수와 충돌하는 것을 방지 할 수 있습니다.


IIFE-즉시 호출 된 함수 표현이라고합니다. 다음은 구문과 사용법을 보여주는 예입니다. 변수 사용 범위를 함수를 넘어서는 것이 아니라 함수까지만 사용하는 데 사용됩니다.

(function () {
  function Question(q,a,c) {
    this.q = q;
    this.a = a;
    this.c = c;
  }

  Question.prototype.displayQuestion = function() {
    console.log(this.q);
    for (var i = 0; i < this.a.length; i++) {
      console.log(i+": "+this.a[i]);
    }
  }

  Question.prototype.checkAnswer = function(ans) {
    if (ans===this.c) {
      console.log("correct");
    } else {
      console.log("incorrect");
    }
  }

  var q1 = new Question('Is Javascript the coolest?', ['yes', 'no'], 0);
  var q2 = new Question('Is python better than Javascript?', ['yes', 'no', 'both are same'], 2);
  var q3 = new Question('Is Javascript the worst?', ['yes', 'no'], 1);

  var questions = [q1, q2, q3];

  var n = Math.floor(Math.random() * questions.length)

  var answer = parseInt(prompt(questions[n].displayQuestion()));
  questions[n].checkAnswer(answer);
})();

IIFE (Immediately invoked function expression)는 스크립트가로드되고 사라지는 즉시 실행되는 함수입니다.

Consider the function below written in a file named iife.js

(function(){
       console.log("Hello Stackoverflow!");
   })();

This code above will execute as soon as you load iife.js and will print 'Hello Stackoverflow!' on the developer tools' console.

For a Detailed explanation see Immediately-Invoked Function Expression (IIFE)


One more use case is memoization where a cache object is not global:

var calculate = (function() {
  var cache = {};
  return function(a) {

    if (cache[a]) {
      return cache[a];
    } else {
      // Calculate heavy operation
      cache[a] = heavyOperation(a);
      return cache[a];
    }
  }
})();

An immediately invoked function expression (IIFE) is a function that's executed as soon as it's created. It has no connection with any events or asynchronous execution. You can define an IIFE as shown below:

(function() {
     // all your code here
     // ...
})();

The first pair of parentheses function(){...} converts the code inside the parentheses into an expression.The second pair of parentheses calls the function resulting from the expression.

An IIFE can also be described as a self-invoking anonymous function. Its most common usage is to limit the scope of a variable made via var or to encapsulate context to avoid name collisions.


The reason self-evoking anonymous functions are used is they should never be called by other code since they "set up" the code which IS meant to be called (along with giving scope to functions and variables).

In other words, they are like programs that "make classes', at the beginning of program. After they are instantiated (automatically), the only functions that are available are the ones returned in by the anonymous function. However, all the other 'hidden' functions are still there, along with any state (variables set during scope creation).

Very cool.


The following code:

(function () {

})();

is called an immediately invoked function expression (IIFE).

It is called a function expression because the ( yourcode ) operator in Javascript force it into an expression. The difference between a function expression and a function declaration is the following:

// declaration:
function declaredFunction () {}

// expressions:

// storing function into variable
const expressedFunction = function () {}

// Using () operator, which transforms the function into an expression
(function () {})

An expression is simply a bunch of code which can be evaluated to a single value. In case of the expressions in the above example this value was a single function object.

After we have an expression which evaluates to a function object we then can immediately invoke the function object with the () operator. For example:

(function() {

  const foo = 10;        // all variables inside here are scoped to the function block
  console.log(foo);

})();

console.log(foo);  // referenceError foo is scoped to the IIFE

Why is this useful?

When we are dealing with a large code base and/or when we are importing various libraries the chance of naming conflicts increases. When we are writing certain parts of our code which is related (and thus is using the same variables) inside an IIFE all of the variables and function names are scoped to the function brackets of the IIFE. This reduces chances of naming conflicts and lets you name them more careless (e.g. you don't have to prefix them).


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:

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:

Object {}
Object {}

Usually, we don't invoke a function immediately after we write it in the program. In extremely simple terms, when you call a function right after its creation, it is called IIFE - a fancy name.


Normally, JavaScript code has global scope in the application. When we declare global variable in it, there is a chance for using the same duplicate variable in some other area of the development for some other purpose. Because of this duplication there may happen some error. So we can avoid this global variables by using immediately invoking function expression , this expression is self-executing expression.When we make our code inside this IIFE expression global variable will be like local scope and local variable.

Two ways we can create IIFE

(function () {
    "use strict";
    var app = angular.module("myModule", []);
}());

OR

(function () {
    "use strict";
    var app = angular.module("myModule", []);
})();

In the code snippet above, “var app” is a local variable now.

참고URL : https://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript

반응형