일단 작성하기전에 내생각부터 말해보자면 코드를 해석하기에 this 바인딩은 특히 JavaScript 초보자에게 혼란스러울수 있다고 생각한다. 직접 변수를 접근하는 방식이 더 간단하고 명확하다고 생각한다.
상황에 따라 다르겠지만, 협업하는 과정에서 누군가가 이해하기가 힘들다면 this바인딩에 명확한 장점을 내세울수 없다면 직접접근이 더 좋은 방법이라고 생각합니다.
하지만 개념자체는 알고 있어야하기 때문에 정리해봅니다.
this는 함수가 호출되는 방식에 따라 다르게 바인딩됩니다. 자바스크립트에서는 실행 컨텍스트(Execution Context)에 의해 this가 결정됩니다.
function globalFunc() {
console.log(this); // window
}
globalFunc();
const obj = {
value: 10,
getValue() {
return this.value;
}
};
console.log(obj.getValue()); // 10
function Person(name) {
this.name = name;
}
const person = new Person('Seulbin');
console.log(person.name); // Seulbin
4.call, apply, bind 메서드:
const person = { name: 'Seulbin' };
function introduce() {
console.log(`My name is ${this.name}`);
}
introduce.call(person); // My name is Seulbin
const obj = {
name: 'Seulbin',
getName: () => {
console.log(this.name); // undefined (전역 스코프의 this 사용)
}
};
obj.getName();
정리: