━━━━ ◇ ━━━━
-/js

[JS] self vs this

👀 self vs this

생활코딩의 JavaScript 강좌를 보다가 selfthis의 차이점에 대해서 문득 궁금해졌다. JavaScript에서 selfthis의 차이점에 대해 알아보자.

✔ JavaScript의 self와 this

this: 현재 함수가 invoking 되는 오브젝트를 참조
self: window를 참조, var self = this와 같은 식으로 함수 내에서 선언되었을 시에는 해당 함수가 invoking 되는 오브젝트의 로컬 스코프를 가리킴 (중첩으로 함수를 리턴하는 곳에서 많이 사용)

✔ 선언

var a = {
    b: "c",
    func: function(){
        var self = this;
        console.log("outer this.b = " + this.b);
        console.log("outer self.b = " + self.b);
          (function(){
            console.log("inner this.b = " + this.b);
              console.log("inner self.b = " + self.b);
        }());
    }
}
a.func();

✔ 사용

outer this.b = c
// this는 오브젝트 a를 가리킴
outer self.b = c
// self는 로컬 스코프 a를 가리킴
inner this.b = undefined
// this는 오브젝트를 가리켜야 하나, invoking 오브젝트가 없으므로 this는 글로벌 오브젝트 window를 가리킴. 하지만 window에는 b라는 속성이 없으므로 undefined
inner self.b = c
// self는 로컬 스코프 a를 가리킴

✔ 글로벌 스코프에서 windows와 self와 this의 관계

console.log( window ); // window
console.log( self );   // window
console.log( this );   // window

console.log( window.window ); // window
console.log( window.self );   // window
console.log( window.this );   // undefined

console.log( self.window );   // window, window.window와 같은 맥락
console.log( self.self );     // window, window.self와 같은 맥락
console.log( self.this );     // undefined, window.this와 같은 맥락

console.log( this.this );     // undefined, window.this와 같은 맥락
console.log( this.window );   // window, window.window와 같은 맥락
console.log( this.self );     // window, window.self와 같은 맥락

👍 참고 사이트

  1. Difference between this and self in JavaScript
  2. (Cocos Creator) JavaScript의 this 와 self의 차이


'- > js' 카테고리의 다른 글

[JS] 자바스크립트 메모리 누수  (0) 2021.06.19
[JS] 비교 연산자  (0) 2021.01.15
[JS] DOM  (0) 2021.01.15
[JS] 연동방식  (0) 2021.01.15
[JS] Hoisting  (0) 2021.01.14
COMMENT