this, call, apply, bind
Chapter 15 - this, call, apply and bind
this
class Person {
constructor(name) {
this.name = name;
}
whatYourName() {
return this.name;
}
}
const person1 = new Person("luas");
const person2 = new Person("envy");
const name1 = person1.whatYourName(); // luas
const name2 = person2.whatYourName(); // envy
멤버내에서는 this
키워드로 현재 실행중인 인스턴스 즉 자신을 지칭할 수 있다. 여기서 this는 클래스가 아니라 인스턴스를 뜻한다. 인스턴스별로 자기자신의 멤버를 참조하여 개별적인 동작을 구현할 수 있다. 상속받은 클래스라면 super
키워드를 통해 부모 클래스를 지칭할 수도 있다.
call, apply, bind
class Person {
constructor(name) {
this.name = name;
}
whatYourName(param1, param2) {
return this.name;
}
}
const person1 = new Person("luas");
const person2 = new Person("envy");
const name1 = person1.whatYourName.call(person2, "some", "thing"); // envy
const name2 = person2.whatYourName.apply(person1, ["some", "thing"]); // luas
const binded = person2.whatYourName.bind(person1);
const name3 = binded("some", "thing"); // luas
함수도 사실 'Object로 구현된 객체'이다. 이 객체는 프로토타입으로 call(), apply(), bind()
를 내장함수로 제공한다. 이 함수는 모두 다 this
를 변환하기 위한 목적으로 사용된다.
위 예제에서 person1.whatYourName()
은 luas를 반환해야 하지만 call()
함수를 호출하면서 첫번째 인자로 person2
변수를 넘김으로써 whatYourName()
함수가 실행되기 전 this가 person2로 치환된 후에 실행된다. 결국 person2.name
이 반환되어 envy 라는 결과값을 얻게된다. apply()
함수는 call과 완벽하게 동일한 작동을 하는데 보면 알겠지만 파라미터를 전달하는 방식이 배열인 차이가 전부이다. bind()
의 경우는 조금 특이한데 해당 함수의 this를 갈아끼운 함수 자체를 반환한다. 반환된 함수는 후에 호출할 수 있다.
초판: 2024. 08. 18. 20:06:19
© 2024 이 문서는 "CC BY 4.0 국제규약" 라이선스로 배포 되었습니다. 모든 권리는 저자에게 있습니다.