본문 바로가기

Development/TIL

this에 대하여

문제

딱히 this 관련하여 문제는 없었다.

하지만 어제 objectId를 생성하는데 this가 관련이 있어서

이어서 정리해보려고 한다.

 

 

시도

일단 가볍게 훑어보자면,

자바스크립트에서 this는 실행 컨텍스트 내에서 현재 객체를 참조하는데 사용된다.

그리고 this가 가리키는 객체는 함수 호출 방식에 따라 결정된다.

 

1. 함수가 객체의 메서드로 호출되면, 'this'는 그 객체를 참조한다.

2. 함수가 일반적으로 호출되면, 'this'는 전역 객체를 참조한다.

3. 함수가 new 연산자와 함께 호출되면, this는 새로운 객체를 참조한다.

4. call, apply, bind 메서드를 사용하여 함수를 호출하면 첫번째 인수로 전달한 객체를 this로 참조한다.

 

this가 가리키는 객체를 확실히 이해하면 메서드와 함수 호출에 대해 적절한 'this' 값을 설정할 수 있다.

이를 이용해서 객체 간의 상호 작용을 처리하거나 함수의 목적에 맞게 적절한 작업을 수행할 수 있다.

 

 

 

해결

const myObj = {
  myMethod() {
    console.log(this); // myObj 객체를 참조합니다.
  }
};

myObj.myMethod(); // myObj 객체를 참조하므로, { myMethod: f }와 같은 객체가 출력됩니다.

function myFunction() {
  console.log(this); // 전역 객체를 참조합니다.
}

myFunction(); // 전역 객체인 window를 참조하므로, Window { ... }와 같은 객체가 출력됩니다.

function Person(name, age) {
  this.name = name;
  this.age = age;
}

const john = new Person("John", 30);
console.log(john); // 새로운 객체 { name: 'John', age: 30 }가 출력됩니다.

function myOtherFunction() {
  console.log(this);
}

const myObj2 = { myProp: "hello" };
myOtherFunction.call(myObj2); // call 메서드를 사용하여 함수를 호출하므로, myObj2 객체를 참조합니다.
// { myProp: 'hello' }와 같은 객체가 출력됩니다.

 

추가 ++

위에서 언급한 call, apply, bind 메서드에 대해 알아보자

 

call은 함수를 호출하는 동시에 this를 설정한다. 첫번째 인자로 this로 바인딩할 값, 그 뒤로는 인자들을 전달한다.

function greeting(name) {
  console.log(`Hello, ${name}! I'm ${this.name}.`);
}

const obj = { name: 'Madonna' };
greeting.call(obj, 'John'); // Hello, John! I'm Madonna

 

 

apply는 함수를 호출하는 동시에 this 값을 설정한다. 첫번째 인자로 this로 바인딩할 값, 두 번째 인자로는 인자들을 배열형태로 전달한다.

function greeting(name) {
  console.log(`Hello, ${name}! I'm ${this.name}.`);
}

const obj = { name: 'Madonna' };
greeting.apply(obj, ['John']); // Hello, John! I'm Madonna.

 

 

bind는 함수의 this 값을 영구적으로 설정한다. 함수를 실행하지는 않고, this 값을 설정한 새로운 함수를 반환한다.

function greeting(name) {
  console.log(`Hello, ${name}! I'm ${this.name}.`);
}

const obj = { name: 'Madonna' };
const boundGreeting = greeting.bind(obj);
boundGreeting('John'); // Hello, John! I'm Madonna.

 

 

 

알게된 것

강의에서 this를 처음 접할 때만 해도 아리송한 개념이었는데

오늘 정리하면서 비교적 확실하게 알게 되었다.

this는 '이것'이다!