this

코딩덕·2023년 6월 5일

💡 this란?

자신이 속한 객체를 나타내는 변수
자신을 호출하는 방법에 따라 다른 값을 가리킨다

JS에서 this는 함수가 호출될때 결정된다!!


기본적인 this 값

기본적인 this값은 window(전역객체)다!!

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

example(); // window

console.log(this); // window

암시적 바인딩

함수의 호출방식에 따라 암시적으로 this값이 달라진다

✅ 예제 1

const person = {
  name: 'Lee',
  printName() {
    console.log(this);
  }
};

// 호출
person.printName(); // { name: 'Lee', printName: [Function: printName] }

중요한 것은 메소드가 어디에 정의되어 있는가가 아니라 메소드를 누가 호출하는가이다.

printName()가 person 객체 내에 정의되어 있다는 점이 아니라, person 객체가 printName() 메소드를 호출 했다는 점을 주목하면 this는 메소드를 호출한 객체를 가리킨다.

✅ 예제 2

const person1 = {
  name: 'Lee',
  printName() {
    console.log(this);
  },
};

const person2 = {
  name: 'Dong',
  printName: person1.printName,
}

person2.printName(); // { name: 'Dong', printName: [Function: printName] }

person2printName()를 호출하고 있으므로 thisperson2가 된다

✅ 예제 3(화살표 함수)

const person = {
  name: 'Lee',
  printName: () => {
    console.log(this); 
  }
};

// 호출
person.printName(); // window

화살표 함수는 선언 시점에서의 상위 스코프가 this 값이 된다.

즉, printName의 this는 자신을 호출한 객체 person이 아니라, 함수 선언 시점의 상위 스코프인 전역객체를 가리킨다.

✅ 예제 4(생성자 함수 new)

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

Person.prototype.printName = function () {
  console.log(this.name);
};

const person = new Person('Lee');
const person2 = new Person('Dong');

// 호출
person.printName(); // Lee
person2.printName(); // Dong

new를 통해 생성자 함수를 호출할 때, 생성자 함수 내부의 this는 새로 생성될 객체가 바인딩된다.

즉, Person 함수 내부의 this는 새로 생성되는 객체를 가르킨다.
따라서 person 객체의 name 프로퍼티에 각각 Lee와 Dong가 할당된다.


명시적 바인딩

함수의 호출방식으로 상관하지 않고 this값을 명시적으로 설정 할 수 있다!

function example(){
  console.log(this.name + a + b);
}

example('Dong', 'Keun'); // window DongKeun 

// bind : 첫번째 인자값으로 전달된 객체에 this를 고정한 새로운 함수를 반환
const usebind = example.bind({name: 'Lee'});
usebind();  // LeeDongKeun

// apply => this값을 바꾼 새로운 함수생성하고 실행(매개변수를 배열로 넘겨줌)
example.apply({name: 'Lee'}, ['Dong', 'Keun']);  // LeeDongKeun

// call => this값을 바꾼 새로운 함수생성하고 실행(매개변수를 나열로 넘겨줌)
example.call({name: 'Lee'}, 'Dong', 'Keun');  // LeeDongKeun

0개의 댓글