Development Tip

(function () {}) () 구조는 어떻게 작동하며 사람들이 왜 그것을 사용합니까?

yourdevel 2020. 10. 11. 11:27
반응형

(function () {}) () 구조는 어떻게 작동하며 사람들이 왜 그것을 사용합니까?


(function() {})()jQuery에 특화된 사촌 (function($) {})(jQuery)은 자바 스크립트 코드에서 항상 팝업됩니다.

이러한 구성은 어떻게 작동하며 어떤 문제를 해결합니까?

감사의 예


JavaScript 프레임 워크의 인기가 높아짐에 따라이 $기호는 다양한 경우에 사용되었습니다. 따라서 가능한 충돌을 줄이기 위해 다음 구성을 사용할 수 있습니다.

(function ($){
  // Your code using $ here.
})(jQuery);

특히, 이것은 주 jQuery 객체를 매개 변수로 전달하는 즉시 실행되는 익명 함수 선언입니다 . 해당 함수 내 에서 다른 프레임 워크가 범위에 있는지 걱정하지 않고 해당 개체를 참조하는 데 사용할 수 있습니다 .$


이것은 변수 범위를 제한하는 데 사용되는 기술입니다. 변수가 전역 네임 스페이스를 오염시키는 것을 방지하는 유일한 방법입니다.

var bar = 1; // bar is now part of the global namespace
alert(bar);

(function () {
   var foo = 1; // foo has function scope
   alert(foo); 
   // code to be executed goes here
})();

1) 익명의 함수를 정의하고 바로 실행합니다.

2) 일반적으로 원치 않는 코드로 전역 네임 스페이스를 오염시키지 않도록 수행됩니다.

3) 몇 가지 메소드를 노출해야합니다. 내부 선언은 "비공개"입니다. 예 :

MyLib = (function(){
    // other private stuff here
    return {
        init: function(){
        }
    };

})();

또는, 또는 :

MyLib = {};
(function({
    MyLib.foo = function(){
    }
}));

요점은 여러 가지 방법으로 사용할 수 있지만 결과는 동일하다는 것입니다.


즉시 호출되는 익명 함수입니다. 먼저 함수를 만든 다음 호출하면 동일한 효과를 얻을 수 있습니다.

(function(){ ... })();

다음과 같이 작동합니다.

temp = function(){ ... };
temp();

명명 된 함수로 동일한 작업을 수행 할 수도 있습니다.

function temp() { ... }
temp();

jQuery 특정이라고 부르는 코드는 jQuery 객체를 사용한다는 의미에서만 가능합니다. 즉시 호출되는 매개 변수가있는 익명 함수입니다.

두 단계로 동일한 작업을 수행 할 수 있으며 원하는 매개 변수로 수행 할 수 있습니다.

temp = function(answer){ ... };
temp(42);

이것이 해결하는 문제는 함수의 코드에 대한 클로즈를 생성한다는 것입니다. 전역 네임 스페이스를 오염시키지 않고 변수를 선언 할 수 있으므로 한 스크립트를 다른 스크립트와 함께 사용할 때 충돌 위험을 줄일 수 있습니다.

jQuery의 특정 경우에는 이름 $를 jQuery의 별칭으로 선언하지 않는 호환성 모드에서 사용합니다. jQuery 객체를 클로저로 보내고 매개 변수 이름을 $로 지정하면 호환성 모드없이 동일한 구문을 사용할 수 있습니다.


여기서는 첫 번째 구성이 변수에 대한 범위를 제공한다고 설명 합니다.

변수는 자바 스크립트의 함수 수준에서 범위가 지정됩니다. 이것은 변수가 블록으로 범위가 지정된 C # 또는 Java와 같은 언어에서 익숙한 것과 다릅니다. 이것이 의미하는 바는 루프 또는 if 문 내에서 변수를 선언하면 전체 함수에서 사용할 수 있다는 것입니다.

함수 내에서 변수의 범위를 명시 적으로 지정해야하는 경우 익명 함수를 사용하여이를 수행 할 수 있습니다. 실제로 익명 함수를 만든 다음 바로 실행할 수 있으며 내부의 모든 변수는 익명 함수로 범위가 지정됩니다.

(function() {
  var myProperty = "hello world";
  alert(myProperty);
})();
alert(typeof(myProperty)); // undefined

이를 수행하는 또 다른 이유 $는 사용 중인 프레임 워크 연산자에 대한 혼란을 제거하기위한 것 입니다. 예를 들어 jQuery를 강제하려면 다음을 수행하십시오.

;(function($){
   ... your jQuery code here...
})(jQuery);

$연산자를 매개 변수로 전달하고 jQuery에서 호출하면 $다른 프레임 워크가로드 된 경우에도 함수 내의 연산자가 jQuery에 잠 깁니다.


이 구조의 또 다른 용도는 클로저에 사용될 지역 변수의 값을 "캡처"하는 것입니다. 예를 들면 :

for (var i = 0; i < 3; i++) {
    $("#button"+i).click(function() {
        alert(i);
    });
}

위의 코드는 세 개의 버튼이 모두 "3"으로 팝업되도록합니다. 반면에 :

for (var i = 0; i < 3; i++) {
    (function(i) {
        $("#button"+i).click(function() {
            alert(i);
        });
    })(i);
}

그러면 예상대로 세 개의 버튼이 "0", "1", "2"로 팝업됩니다.

그 이유는 클로저 가 해당 변수의 현재 값을 보유하는 둘러싸는 스택 프레임에 대한 참조를 유지하기 때문 입니다. 클로저가 실행되기 전에 이러한 변수가 변경되면 클로저는 클로저가 생성 된 시점의 값이 아닌 최신 값만 볼 수 있습니다. 위의 두 번째 예에서와 같이 다른 함수 안에 클로저 생성을 래핑하면 변수의 현재 값 i이 익명 함수의 스택 프레임에 저장됩니다.


이것은 폐쇄 로 간주됩니다 . 포함 된 코드가 자체 어휘 범위 내에서 실행됨을 의미합니다. 즉, 새 변수와 함수를 정의 할 수 있으며 클로저 외부의 코드에서 사용되는 네임 스페이스와 충돌하지 않습니다.

var i = 0;
alert("The magic number is " + i);

(function() {
   var i = 99;
   alert("The magic number inside the closure is " + i);
})();

alert("The magic number is still " + i);

This will generate three popups, demonstrating that the i in the closure does not alter the pre-existing variable of the same name:

  • The magic number is 0
  • The magic number inside the closure is 99
  • The magic number is still 0

They are often used in jQuery plugins. As explained in the jQuery Plugins Authoring Guide all variables declared inside { } are private and are not visible to the outside which allows for better encapsulation.


As others have said, they both define anonymous functions that are invoked immediately. I generally wrap my JavaScript class declarations in this structure in order to create a static private scope for the class. I can then place constant data, static methods, event handlers, or anything else in that scope and it will only be visible to instances of the class:

// Declare a namespace object.
window.MyLibrary = {};

// Wrap class declaration to create a private static scope.
(function() {
  var incrementingID = 0;

  function somePrivateStaticMethod() {
    // ...
  }

  // Declare the MyObject class under the MyLibrary namespace.
  MyLibrary.MyObject = function() {
    this.id = incrementingID++;
  };

  // ...MyObject's prototype declaration goes here, etc...
  MyLibrary.MyObject.prototype = {
    memberMethod: function() {
      // Do some stuff
      // Maybe call a static private method!
      somePrivateStaticMethod();
    }
  };
})();

In this example, the MyObject class is assigned to the MyLibrary namespace, so it is accessible. incrementingID and somePrivateStaticMethod() are not directly accessible outside of the anonymous function scope.


That is basically to namespace your JavaScript code.

For example, you can place any variables or functions within there, and from the outside, they don't exist in that scope. So when you encapsulate everything in there, you don't have to worry about clashes.

The () at the end means to self invoke. You can also add an argument there that will become the argument of your anonymous function. I do this with jQuery often, and you can see why...

(function($) {

    // Now I can use $, but it won't affect any other library like Prototype
})(jQuery);

Evan Trimboli covers the rest in his answer.


It's a self-invoking function. Kind of like shorthand for writing

function DoSomeStuff($)
{
}

DoSomeStuff(jQuery);

What the above code is doing is creating an anonymous function on line 1, and then calling it on line 3 with 0 arguments. This effectively encapsulates all functions and variables defined within that library, because all of the functions will be accessible only inside that anonymous function.

This is good practice, and the reasoning behind it is to avoid polluting the global namespace with variables and functions, which could be clobbered by other pieces of Javascript throughout the site.

To clarify how the function is called, consider the simple example:

If you have this single line of Javascript included, it will invoke automatically without explicitly calling it:

alert('hello');

So, take that idea, and apply it to this example:

(function() {
    alert('hello')
    //anything I define in here is scoped to this function only
}) (); //here, the anonymous function is invoked

The end result is similar, because the anonymous function is invoked just like the previous example.


Because the good code answers are already taken :) I'll throw in a suggestion to watch some John Resig videos video 1 , video 2 (inventor of jQuery & master at JavaScript).

Some really good insights and answers provided in the videos.

That is what I happened to be doing at the moment when I saw your question.


function(){ // some code here }

is the way to define an anonymous function in javascript. They can give you the ability to execute a function in the context of another function (where you might not have that ability otherwise).

참고URL : https://stackoverflow.com/questions/1639180/how-does-the-function-construct-work-and-why-do-people-use-it

반응형