Chrome Pointer

Javascript

this, call, apply, bind

Frontend Diary 2025. 1. 15. 14:50

JavaScript에서 this현재 객체나 인스턴스를 가리키는 변수라고 할 수 있다.

그러나 this의 값은 함수의 호출 방식에 따라 다르게 결정된다.

 

예:브라우저에서 전역 코드에서 this는 window 객체를 참조한다.

console.log(this);  // 브라우저에서는 window 객체

 

 

예: this는 메서드를 호출한 객체를 참조한다.

 

const person = {
  name: 'Tom',
  greet: function() {
    console.log(this.name); // this는 person 객체를 참조
  }
};
person.greet(); // Tom

 

 

call, apply, bind는 모두 this를 명시적으로 설정할 때 사용되는 메서드이다. 각각의 동작 방식은 약간 다르다.

 

 

call - call 메서드는 this를 지정한 객체로 설정하고, 즉시 함수를 실행한다. 인자는 개별적으로 전달된다. 

function greet() {
  console.log(`Hello, ${this.name}`);
}

const person = { name: 'Tom' };
greet.call(person); // Hello, Tom

 

 

apply - apply 메서드도 this를 지정한 객체로 설정하고, 즉시 함수를 실행한다. 다만, 인자는 배열 형식으로 전달된다.

function greet(age, city) {
  console.log(`Hello, ${this.name}. You are ${age} years old and live in ${city}.`);
}

const person = { name: 'Tom' };
greet.apply(person, [25, 'Seoul']); // Hello, Tom. You are 25 years old and live in Seoul.

 

 

bind - bind는 함수를 즉시 실행하지 않고, this를 미리 설정한 새로운 함수를 반환한다. 이 반환된 함수는 나중에 호출될 수 있다.

function greet() {
  console.log(`Hello, ${this.name}`);
}

const person = { name: 'Tom' };
const boundGreet = greet.bind(person);
boundGreet(); // Hello, Tom

 

'Javascript' 카테고리의 다른 글

Callback hell, sync and async function  (0) 2025.01.17
CSR vs SSR  (1) 2025.01.17
Data Type  (0) 2025.01.15
변수 선언, 초기화, 할당의 차이점  (0) 2025.01.15
Hoisting이란 무엇인가?  (0) 2025.01.15