가끔 피드에 bind, apply, call에 대한 컨텐츠가 나온다. 그럼 어? 옛날에 공부했던건데 지금 기억이 안나네.. 이거 현업에서도 쓰이지 않는거 같은데 왜 내가 이걸 배웠었는지 이걸 꼭 알아야 하는지 의문이 들었다.
그래서 이 글로 인하여 내 궁금증을 해소해보려 한다.
jQuery로 웹서비스를 만들 때 몇 번 bind를 이용해서 작성된 코드를 본적이 있다.
하지만 react로 몇 년동안은 bind, apply, call은 써본적도 없고 누가 작성한 코드를 본적도 없는거 같다.
bind, apply, call에 대해 간단히 살펴 보고 jQuery를 사용할 때는 왜 사용했었는지, 지금은 왜 사용안하는지, 여전히 알 필요가 있는지 알아보자.
기본 개념
bind, call, apply는 함수의 this를 강제로 지정할 때 필요한 메소드
bind
함수의 this를 미리 고정하고 싶을 때
const obj = { name: 'chuck' };
function sayName() { console.log(this.name); }
const boundSayName = sayName.bind(obj);
boundSayName(); // chuck
call
함수를 즉시 호출하면서 this를 지정할 때
function greet(msg) { console.log(msg + ', ' + this.name); }
greet.call({ name: 'chuck' }, 'Hello'); // Hello, chuck
apply
call과 똑같지만 인자를 배열로
function greet(msg) { console.log(msg + ', ' + this.name); }
greet.apply({ name: 'chuck' }, ['Hello']); // Hello, chuck
jQuery로 개발할 때 bind는 왜 필요했나?
이벤트 핸들러 안의 this는 기본적으로 이벤트가 걸린 DOM 요소를 가리킴. 하지만 가끔은 내가 만든 객체의 메서드에서 this를 유지한 채 이벤트 핸들러를 실행하고 싶을 때가 있음.
<html>
<body>
<button id="btn">Click me</button>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</body>
<script>
function App() {
this.name = 'Chuck'
this.init = function () {
$('#btn').on('click', this.handleClick) // ❌ this는 버튼 DOM이 됨
}
this.handleClick = function () {
console.log('this', this) // <button id="btn">Click me</button>
console.log('name', this.name) // empty string
}
}
const app = new App()
app.init()
</script>
</html>
bind로 handleClick 함수를 app instance의 this 로 고정
<html>
<body>
<button id="btn">Click me</button>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</body>
<script>
function App() {
this.name = 'Chuck'
this.init = function () {
$('#btn').on('click', this.handleClick.bind(this)) // ✅ this는 App 인스턴스로 고정
}
this.handleClick = function () {
console.log('this', this) // { "name": "Chuck"}
console.log('name', this.name) // Chuck
}
}
const app = new App()
app.init()
</script>
</html>
jQuery로 개발할 때 call는 왜 필요했나?
jQuery에서 기존 함수를 다른 context에서 실행하고 싶을 때
<html>
<body>
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<div class="item">Item 4</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</body>
<script>
function highlight() {
$(this).css('background-color', 'yellow')
}
$('.item').each(function () {
highlight.call(this) // this를 현재 .item 요소로 바꿔서 실행
})
</script>
</html>
jQuery로 개발할 때 apply는 왜 필요했나?
인자의 개수가 유동적이고, 배열로 전달돼야 하는 함수에 this를 지정해 실행할 때
function logUserInfo(age, country) {
console.log(`${this.name}, ${age}, ${country}`);
}
const user = { name: 'Chuck' };
const info = [30, 'Korea'];
logUserInfo.apply(user, info); // Chuck, 30, Korea
react로 개발하다보면 bind, call, apply는 왜 보기 드문가?
React의 구조 자체가 this 문제를 회피하거나 해결해주기 때문
- 클래스 컴포넌트에서 함수형 컴포넌트 오면서 핸들러에 this bind 해줄 필요가 없음
- useState, useEffect도 전부 클로저 기반이라 this가 아예 안 쓰임.
- React는 "함수를 즉시 실행"하는 구조가 아님.
그렇다면, bind, call, apply 배울 필요는 없는가?
bind | 꼭 알아야 함 | 실무에서도 종종 씀 | 이벤트 핸들러, this 고정 |
call | 개념은 알아야 함 | 직접 쓸 일 거의 없음 | 남의 코드 분석/디버깅 |
apply | 알아두면 좋음 | 직접 쓸 일 거의 없음 | arguments/배열 → 함수 호출 |
'IT > javascript' 카테고리의 다른 글
[JS] var 에 대해서 그리고 hoisting 까지 (1) | 2024.09.12 |
---|---|
[javascript] import 자세하게 파해쳐보자 (2) | 2024.09.12 |
[JS] 제너레이터 함수 (generator function) (0) | 2024.07.07 |
[JS] prototype (0) | 2024.04.30 |
[JS] if else 리팩토링 (중첩 조건문 처리하기) > 코드 변환 스냅샷 (0) | 2024.04.29 |