This란?
- this는 스코프와 관계가 있음, JS는 함수, 배열, 일반적인 객체를 다 객체로 보는데, this가 어디에 묶여있는지를 아는 것에 따라서 처리하고 활용도가 다름
- this가 의도와 다르게 호출되고 동작할 수 있기에 bind 메소드를 활용해서 처리하는 경우도 있음
- 참고자료
암시적 바인딩
- NodeJS 환경에서 전역 객체는 Global이고 브라우저에서 객체는 window 객체임, 하지만 this는 또 다르게 적용함
- 그리고 함수 공간에서의 this도 다름, this가 전역공간을 바라보기에 여기선 브라우저도 window가 됨
- 객체에서의 this는 객체 내 메서드에서의 호출되는 대상의 객체를 바라봄
const obj2 = {
name: 'obj',
depth: {
name: 'nested obj',
method: function() {
return this.name
}
}
}
obj2.depth.method()
- 이를 안전하게 만들어주는 것을 명시적인 바인딩으로 this를 묶어줌(함수라고 해서 무조건 전역공간을 바라보지 않기 때문임)
명시적 바인딩
call
, apply
, bind
내장 메소드를 통해서 this를 명시적으로 바인딩 할 수 있음
- JS에서는 var 키워드를 쓰면 전역 객체로 들어가버리기에 const로 예시를 썼음
- 아래와 같은 케이스에서 function을 쓰려고 할 때, 명시적인 바인딩을 통해서 this의 바운더리를 정해서 함수를 선택해서 쓸 수 있음
const person = {
name: 'Kevin',
sayName: function() {
return this.name + '입니다';
},
};
const zero = {
name: 'Base',
sayName: function() {
return this.name + '입니다';
},
};
function sayFullName(firstName) {
return firstName + this.sayName()
}
const result = sayFullName.call(person, 'Hart');
const result2 = sayFullName.call(zero, 'Oh');
function sayFullName(firstName) {
return arguments[0] + this.sayName()
}
const result3 = sayFullName.apply(person, ['Oh', 'Kim']);
const result4 = sayFullName.apply(zero, ['Zero', 'Base']);
function sayFullName(firstName) {
return firstName + this.sayName()
}
const sayFullNamePerson = sayFullName.bind(person);
const sayFullNameZero = sayFullName.bind(zero);
console.log(sayFullNamePerson('oh'));
console.log(sayFullNameZero('zero'));