Development Tip

자바 스크립트 익명 함수 끝에 ".call (this)"을 쓰는 이유는 무엇입니까?

yourdevel 2020. 12. 30. 19:46
반응형

자바 스크립트 익명 함수 끝에 ".call (this)"을 쓰는 이유는 무엇입니까?


이 질문에 이미 답변이 있습니다.

나는 다음과 같이 작성된 자바 스크립트를 본 적이있다 (데모에 있었고 실제 코드는 없지만 이것이 정상임을 암시했다).

(function() {    

    var a = 1;

    this.sayA = function() {
        alert(a);
    }

}).call(this);

sayA();

변수 a를 전역 적으로 사용할 수 없도록 익명 함수로 작성되었다고 가정합니다 .

요점이 무엇일까요 .call(this)? 이 함수는 중첩되지 않았으므로 this단지 창이었습니다. ()마지막에 쓰는 것과 어떻게 다른 가요?


이 시도:

function Foo() {

  (function () {
    console.log(this);
    // > Foo
  }).call(this);

  (function () {
    console.log(this);
    // > undefined in strict mode, or Window in non strict mode
  })();
}

var bar = new Foo;

따라서 어떤 이유로 든 이것을 사용하는 경우 , 특히 사용자 정의 개체 유형의 인스턴스 를 만들 때 IIFE가의 멤버 함수 인 것처럼 작동 하도록 만드는 방법 Foo입니다.


이 비디오 에 대한 John Resig의 이야기를 방금 보았을뿐만 아니라 이것에 대해 궁금했습니다 . Yoshi는 훌륭한 답변을 받았지만 이해하기 위해 콘솔 로그에서 약간 테스트해야했으며 그의 답변에 대한이 수정이 처음에는 나처럼 문제가 있었던 일부 사람들에게 도움이 될 것이라고 생각했습니다.

function Foo() {
  this.foo = true;
  (function () {
      console.log("Foo = " + this.foo);
      // Outputs undefined
  }());
  (function () {
      console.log("Foo = " + this.foo);
      // Outputs true
  }).call(this);

  (function () {
      console.log(this);
      // Outputs undefined in strict mode, or Window in non strict mode
      // Anonymous functions usually default to the global scope
  })();
}

var bar = new Foo;

.call (this)이 기본적으로 현재 컨텍스트를 익명 함수에 전달할 수있는 기능을 제공한다는 것을 보여 주면서 첫 번째와 두 번째 항목을 나란히 보는 것이 조금 더 이해가되었습니다.

질문에 감사 드리며 명확한 답변에 대해 Yoshi에게 감사드립니다!


Since this function was not nested, this was just the window. How does it differ from just writing () at the end?

No - not in strict mode:

  1. If the function code is strict code, set the ThisBinding to thisArg.
  2. Else if thisArg is null or undefined, set the ThisBinding to the global object.

In strict mode, the this is just directly set to the given value, which is undefined for a normal call. Therefore, .call(this) is used to pass the global object explicitly in. You can try this in the console:

> (function() { "use strict"; console.log(this); })()
undefined
> (function() { "use strict"; console.log(this); }).call(this)
Window

It might not make a difference for sloppy code, but it's a good practise and future-compatible :-)


this passed to the function sets the context of the execution, so inside your anonymous function this refers to the window.

You can than write this.alert('');.

ReferenceURL : https://stackoverflow.com/questions/8035822/why-write-callthis-at-the-end-of-an-javascript-anonymous-function

반응형