program tip

JavaScript에서 이것과 self의 차이점

radiobox 2020. 8. 27. 07:39
반응형

JavaScript에서 이것과 self의 차이점


모두가 this자바 스크립트에서 알고 있지만 여기self 와 같이 야생에서 발생하는 경우도 있습니다.

그래서, 차이 무엇 thisself자바 스크립트는?


다른 곳으로 설정하지 않는 한,의 값 self입니다 window때문에 자바 스크립트 는 모든 속성에 액세스 할 수 x의를 window간단하게 x대신, window.x. 따라서, self정말 window.self서로 다른 인 this.

window.self === window; // true

전역 범위에서 실행되고 엄격 모드가 아닌 함수를 사용하는 경우 this기본값은 window이므로

function foo() {
    console.log(
        window.self === window, // is self window?
        window.self === this,   // is self this?
        this === window         // is this window?
    );
}
foo(); // true true true

다른 컨텍스트에서 함수를 사용하는 경우은 this해당 컨텍스트를 참조하지만 self여전히 window.

// invoke foo with context {}
foo.call({}); // true false false

여기 에서 Window 개체window.self 에 대한 W3C 2006 작업 초안에 정의 된 내용을 찾을 수 있습니다 .


여기에 늦었지만 this이해하는 데 도움이 될 수있는 한 가지 예를 보았습니다 .

var myObject = {
 foo: "bar",
 func: function() {
    var self = this;
    console.log("outer func:  this.foo = " + this.foo);
    console.log("outer func:  self.foo = " + self.foo);
    (function() {
        console.log("inner func:  this.foo = " + this.foo);
        console.log("inner func:  self.foo = " + self.foo);
    }());
  }
};
myObject.func();

O / P

outer func:  this.foo = bar
outer func:  self.foo = bar
inner func:  this.foo = undefined
inner func:  self.foo = bar

ECMA 5 이전에는 this내부 함수에서 전역 창 개체를 참조했습니다. 반면 ECMA 5에서는 this내부 기능이 정의되지 않았습니다.


사람들이 서비스 워커의 맥락에서 이것을 접할 수 있기 때문에 이것에 약간 추가되며,이 경우 약간 다른 것을 의미합니다.

서비스 워커 모듈에서 이것을 볼 수 있습니다.

self.addEventListener('install', function(e) {
  console.log('[ServiceWorker] Install');
});

Here self refers to the WorkerGlobalScope, and this is the standard method for setting event listeners.

From Mozilla docs:

By using self, you can refer to the global scope in a way that will work not only in a window context (self will resolve to window.self) but also in a worker context (self will then resolve to WorkerGlobalScope.self).

참고URL : https://stackoverflow.com/questions/16875767/difference-between-this-and-self-in-javascript

반응형