Frontend/Javascript
javascript 함수 호출 방식에 따른 this 동적 바인딩
개발하는루루
2023. 4. 4. 17:44
this 바인딩은
함수 호출 방식, 즉 함수가 어떻게 호출되었는지에 따라 동적으로 결정된다.
함수의 상위 스코프를 결정하는 방식인 렉시컬 스코프는 함수 정의가 평가되어 함수 객체가 생성되는 시점에 상위 스코프를 결정한다. 하지만 this 바인딩은 함수 호출 시점에 결정된다.
this는 자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수다.
this를 통해 자신이 속한 객체 또는 자신이 생성할 인스턴스의 프로퍼티나 메서드를 참조할 수 있다.
아래는 일반 함수 내부, 메서드 내부, 생성자 함수 내부에서의 this 사용의 예시이다.
// this는 어디서든지 참조 가능하다.
// 전역에서 this는 전역 객체 window를 가리킨다.
console.log(this); //window
function square (number) {
// 일반 함수 내부에서 this는 전역 객체 window를 가리킨다.
console.log(this); // window
return number * number;
}
square(2);
const person = {
name: 'Lee',
getName() {
// 메서드 내부에서 this는 메서드를 호출한 객체를 가리킨다.
console.log(this); // {name: "Lee", getName: f}
return this.name;
}
};
console.log(person.getName()); // Lee
function Person(name) {
this.name = name;
// 생성자 내부 함수에서 this는 생성자 함수가 생성할 인스턴스를 가리킨다.
console.log(this); // Person {name:"Lee"}
}
const me = new Person('Lee');
console.log(me.name) // Lee