자바스크립트 this

김민우·2022년 12월 1일
0

스파르타 내배캠4기

목록 보기
29/73

1. 상황에 따라 달라지는 this

1- 1 this는 실행 컨텍스트가 생성될 때 결정(this binding) === this는 함수를 호출할 때 결정

전역 공간에서의 this

1. 전역 공간에서 this는 전역 객체를 가리킴

2. window(브라우저 환경), global(node 환경)

console.log(this);
console.log(window);
console.log(this === window); //true

1-2 메서드로서 호출할 때 그 메서드 내부에서의 this

함수 vs 메서드

1. 기준 : 독립성
2. 함수 : 그 자체로 독립적인 기능을 수행
3. 메서드 : 자신을 호출한 대상 객체에 관한 동작을 수행

함수와 메서드가 호출될 때, this는 각각 다르게 할당

var func = function (x) {
console.log(this, x);
};
func(1); // Window { ... } 1
var obj = {
method: func,@20221116일
this2};
obj.method(2); // { method: f } 2

함수로서의 호출과 메서드로서의 호출 구분 기준 : . []

var obj = {
method: function (x) { console.log(this, x) }
};
obj.method(1); // { method: f } 1
obj['method'](2); // { method: f } 2

메서드 내부에서의 this

var obj = {
methodA: function () { console.log(this) },
inner: {
methodB: function() { console.log(this) },
}
};
obj.methodA(); // this === obj
obj['methodA'](); // this === obj
obj.inner.methodB(); // this === obj.inner
obj.inner['methodB'](); // this === obj.inner
obj['inner'].methodB(); // this === obj.inner
obj['inner']['methodB'](); // this === obj.inner

함수로서 호출할 때 그 함수 내부에서의 this

함수 내부에서의 this

1. 어떤 함수를 함수로서 호출할 경우, this는 지정되지 않음(호출 주체가 없으므로)
2. 실행컨텍스트를 활성화할 당시 this가 지정되지 않은 경우, this는 전역 객체를 바
라봄
3. 따라서, 함수로서 ‘독립적으로’ 호출할 때는 this는 전역 객체

메서드의 내부함수에서의 this

1. 메서드의 내부라고 해도, 함수로서 호출한다면 this는 전역 객체

var obj1 = {
outer: function() {
console.log(this);
var innerFunc = function() {
console.log(this);
}
innerFunc();
var obj2 = {
innerMethod: innerFunc
this3};
obj2.innerMethod();
}
};
obj1.outer();

2. this 바인딩에 관해서는 함수를 실행하는 당시의 주변 환경(메서드 내부인지, 함수
내부인지)은 중요하지 않고, 오직 해당 함수를 호출하는 구문 앞에 점 또는 대괄호
표기가 있는지가 관건임!

profile
개발자로서 한걸음

0개의 댓글