Programing

이 관행은 JavaScript에서 무엇이라고 부릅니까?

lottogame 2020. 12. 25. 08:49
반응형

이 관행은 JavaScript에서 무엇이라고 부릅니까?


다음과 같은 함수로 JavaScript 코드를 래핑하면 :

(function(){

  var field = ...;
  function doSomthing(){...
  ...


})();

나는 이것이 많은 웹 페이지에서 저에게 범위 문제를 해결한다는 것을 알았습니다. 이 관행을 무엇이라고 부릅니까?


패턴이라고 자기 호출 하는 자가 호출 기능 . 클로저를 생성 할 수 있지만 이는 패턴 자체가 아니라 패턴의 효과 (아마도 의도 한 효과)입니다.


아래 주석에 대해 조금 명확히하기 위해, 대부분 의 경우 클로저를 생성 할 때 변수 범위를 해당 로컬 클로저로 유지합니다. 전역 변수를 생성하지 않기 위해 변수를 깨끗하게 유지하고 해당 변수에 대한 잠재적 인 원치 않는 변경을 방지합니다.

몇 가지 훌륭한 대답은 설명하는 것이 여기 있습니다 이유를 좀 더 : 자바 스크립트 폐쇄 작업을 수행하는 방법?

해당 범위 내의 무언가가 외부 범위에 노출 될 때만 클로저를 생성 하는 것입니다. 일반적 으로 그렇습니다.하지만 더 많은 코드를 보지 않고는 귀하의 예제를 확신 할 수 없습니다. 아무것도 노출되지 않으면 클로저가 생성되지 않습니다 ... 그렇지 않으면 즉시 실행되는 익명 함수입니다.

})();반대로 끝 형식은 });매개 변수없이 즉시 실행되도록 해당 클로저를 실제로 호출하는 것입니다. 당신은 예를 들어 그 안에 무언가를 가지고 있다면 })(something);것을 다음 something여기에 첫 번째 인수로 전달 될 것입니다 : (function(somethingParam){.


래핑 함수는 익명 (이름이없고 변수에 할당되지 않음) 자체 실행 (즉시 자체적으로 실행 됨) 함수라고합니다.

이 패턴의 정확한 이름을 본 기억이 없지만 변수가 전역 범위로 누출되는 것을 방지합니다.


Ben Alman은이 "패턴"에 대해 일반적으로 사용되는 용어에 대해 흥미로운 주장을 제시합니다.

이에 대한 그의 블로그 게시물은 여기 (http://benalman.com/news/2010/11/immediately-invoked-function-expression/) 입니다.

그의 게시물이 너무 길면 여기에 요약이 있습니다 (이 요약은 많은 부분을 생략하므로 여전히 읽는 것이 좋습니다).

명명 된 함수가 자체 실행 / 호출되도록하려면 다음과 같아야합니다.

// Hello, my name is "foo". I am a named function.
// When I am invoked I invoke my self when I am invoked.
function foo(){
   foo();
}

익명 함수가 자체 실행 / 호출되도록하려면 다음과 같아야합니다.

// Hello, I have no name...
//   (though I am assigned to the variable "foo" it's not who I am).
// When I am invoked I invoke my self when I am invoked.
// In ECMAScript 5 I no longer work. :-(
var foo = function(){
    arguments.callee();
};

익명 함수를 즉시 실행 / 호출하려면 다음과 같아야합니다.

// Hello, I have no name. I am immediately invoked.
// People sometimes call me a "self-invoking anonymous function"...
//    even though I don't invoke myself.
// Ben Alman calls me an "Immediately-Invoked Function Expression"...
//    or "iffy" for short.
(function(){ /...code.../ }());

문제에 대한 내 생각 :

다른 답변은 정확합니다. 당신이 묻는 것은 일반적으로 "익명 함수를 호출하는자가 호출"이라고합니다.
그러나 그 용어는 실제로 일어나는 일을 정확하게 반영하지 않습니다. "즉시 호출 된 함수 표현식"(줄여서 "iffy"라고도 함)이 더 적절한 용어처럼 보입니다.


친구들에게 깊은 인상을 남길 수있는 재미있는 사실 :

다음과 같이 Iffy를 만들 수도 있습니다.

!function(){
   alert("immediately invoked!");
}();

또는

+function(){
   alert("immediately invoked!");
}();

또는 당신이 정말로 cRaZy라면 ( ) :

!1%-+~function(){
   alert("immediately invoked!");
}();

대부분의 브라우저에서 (모두는 아니지만 확실하지 않음) 효과는 동일합니다 (페이스 북은 !버전 사용).


Douglas Crockford and the YUI team call it the module pattern.


What is this practice called?

It's called an immediately-invoked function expression, in short: IIFE. It defines a function in an expression, which is then executed on its own (without assigning the function to any identifier). It sometimes is also called immediately executed function expression (IEFE).

Before Ben Alman wrote his blog post on them, they were also known as self-invoking (anonymous) functions, a term which became uncommon since then. It was technically imprecise, hinting at a recursive invocation which does not actually happen.

For details on the syntax see Explain the encapsulated anonymous function syntax and Location of parenthesis for auto-executing anonymous JavaScript functions?.

I noticed that this fixes scoping problems for me on a lot of web pages.

Yes, the purpose of this pattern is to introduce an extra scope by executing a function.

The pattern also is sometimes extended with a return value, known as the (revealing) module pattern, or with a name for the function to allow recursive invocations.


It's been around longer than "patterns". It is a common idiom in scheme/lisp primarily used for encapsulation especially when doing meta programming.


Version 1:-

function mySpace()
{
    var obj = {};

    obj.name = "Deepak";
    obj.whoami = function ()
    {
        return obj.name;
    }

    window['myObject'] = obj;
}

mySpace();

myName = myObject.whoami();

console.log(myName);

Version 2:-

(function(){

    var obj = {};

    obj.name = "Deepak";
    obj.whoami = function ()
    {
        return obj.name;
    }

    window['myObject'] = obj;
})();

myName = myObject.whoami();

console.log(myName);

We are not calling any named function in Version 2 to initialise myObject but its available to global scope.

You are only linking <script src="jquery.min.js"></script> and $ object is available for use. That style is known as self invocation function.

ReferenceURL : https://stackoverflow.com/questions/3720283/what-is-this-practice-called-in-javascript

반응형