[JavaScript] self vs this

박우현·2020년 12월 22일
0
post-thumbnail

👌 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를 가리킴

글로벌 스코프에서 windowsselfthis의 관계를 알아보면,

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와 같은 맥락

👍 참고 사이트

0개의 댓글