this란?

dr7204·2025년 4월 21일

this란?

함수를 호출할 때 생성되는 실행 컨텍스트 객체를 말한다.

this는 실행 컨텍스트가 생성될 때 결정되며, 함수가 호출되는 방식에 따라 다르게 바인딩된다.

전역 컨텍스트 (Global Context)

전역에서 this를 참조하면 브라우저에서는 전역(window) 객체를 가리킨다.

console.log(this); //window

일반 함수 호출 (Default Binding)

함수 내부에서 this를 사용하면, 전역(window) 객체를 가리킨다.

non-strict mode 에서는 전역 객체를, strict mode 에서는 undefined

function foo() {
	console.log(this); //window
}
foo();

메서드 호출 (Implicit Binding)

객체의 메소드로 호출되었을 경우, this는 그 객체를 가리킨다.

const obj = {
	name: "Peter",
	funcD: () {
		console.log(this.name);
	}
}

obj.funcD();
//Peter

생성자 함수 (New Binding)

new 키워드를 사용하여 함수를 호출하면, 새로운 객체가 생성되면 this그 객체를 가리킨다.

function Person(name) {
    this.name = name;
}
const me = new Person('Alice');
console.log(me.name); // "Alice"
****

명시적 바인딩 (Explicit Binding)

.call(), .apply(), .bind() 메서드를 사용하면 this명시적으로 지정할 수 있다.

function greet() {
    console.log(this.name);
}

const user = { name: 'Bob' };
greet.call(user);  // "Bob"
greet.apply(user); // "Bob"

const boundGreet = greet.bind(user);
boundGreet();      // "Bob"
  • call()apply() 는 즉시 실행하며, 첫 번째 인자로 this를 지정한다.
  • bind()는 새로운 함수를 반환하여 나중에 실행할 수 있도록 한다.

화살표 함수 (Lexical Binding)

화살표 함수의 경우, this를 바인딩하지 않고 선언된 위치에서 this상속한다.

즉 자신을 감싸고 있는 상위 스코프this를 그대로 사용한다.

  1. 객체에서 사용되었을 경우, 해당 객체가 아니고 상위 스코프인 전역 객체를 참조한다.
const obj = {
  name: "Alice",
  funcD: () => {
    console.log(this.name);
  },
};

obj.funcD(); 
//undefined
  1. 객체의 메서드를 외부 함수로 내부에서 사용되었을 경우
const obj = {
  name: "Alice",
  funcD: function () {
	  setTimeout(() => {
	  console.log(this.name);
	  }, 1000)
  },
};

obj.funcD();
//Alice

상위 스코프인 funcD 함수의 this를 상속받는다.

funcD는 obj 객체의 메소드이기 때문에, this는 ****obj 객체에 바인딩되어있다.

DOM addEventListener() 의 경우, this는 e.currentTarget과 같다.

정리

호출 방식this 값
전역 실행window (브라우저) / global (Node.js)
일반 함수 호출window (strict mode에서는 undefined)
메서드 호출호출한 객체
생성자 함수 호출새로 생성된 객체
call / apply / bind 사용명시적으로 지정된 객체
화살표 함수상위 스코프의 this

0개의 댓글