JavaScript에서 이것과 self의 차이점
모두가 this
자바 스크립트에서 알고 있지만 여기self
와 같이 야생에서 발생하는 경우도 있습니다.
그래서, 차이 무엇 this
과 self
자바 스크립트는?
다른 곳으로 설정하지 않는 한,의 값 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
'program tip' 카테고리의 다른 글
PHP 5.4에서 엄격한 표준 비활성화 (0) | 2020.08.27 |
---|---|
Java에서 오류 방지 및 오류 방지 반복기는 무엇입니까? (0) | 2020.08.27 |
각 행의 최대 값을 가진 열 이름을 찾습니다. (0) | 2020.08.27 |
PHP에서 배열 키로 사용되는 숫자 문자열 (0) | 2020.08.27 |
데이터베이스의 모든 저장 프로 시저에 대한 실행 권한을 사용자에게 부여 하시겠습니까? (0) | 2020.08.27 |