πŸ‘©‍πŸ’»/JavaScript

[JavaScript] call, apply and bind

ν•œλ‚˜ 2021. 5. 5. 23:15

μžλ°”μŠ€ν¬λ¦½νŠΈμ—μ„œλŠ” ν•¨μˆ˜λ„ 객체둜 닀뀄진닀. call(), apply(), bind()λŠ” λͺ¨λ‘ ν•¨μˆ˜ 싀행을 μ œμ–΄ν•˜κΈ° μœ„ν•΄ μ‚¬μš©λ˜λŠ” λ©”μ†Œλ“œμ΄λ‹€. call()κ³Ό apply()λŠ” ES5에 λ„μž…λœ 문법이고 bind()λŠ” κ·Έν›„ ES5에 λ„μž…λ˜μ—ˆλ‹€.

ν•¨μˆ˜λ₯Ό μ¦‰μ‹œ μ‹€ν–‰ν•˜κ³ μž ν•  λ•ŒλŠ” call()κ³Ό apply()λ₯Ό μ‚¬μš©ν•˜κ³ , bind()λŠ” λ‚˜μ€‘μ— bound된 ν•¨μˆ˜λ₯Ό 리턴 λ°›μ•„ μ‚¬μš©ν•˜λ―€λ‘œ 이후에 싀행될 ν•¨μˆ˜λ₯Ό μƒκ°ν•˜λ©° 써야 ν•œλ‹€.

const user = {
    name: 'Hannah'
}
const profile = function (location, language) {
    return `${this.name} is a ${language} programmer, who lives in ${location}`;
}

console.log(profile.call(user, 'Seoul', 'JavaScript'));
// Hannah is a JavaScript programmer, who lives in Seoul

const arguments = ['Seoul', 'JavaScript'];
console.log(profile.apply(user, arguments))
// Hannah is a JavaScript programmer, who lives in Seoul

 

call()κ³Ό apply()λŠ” 각각 첫 번째 인자둜 λ°›λŠ” 값을 this μ»¨ν…μŠ€νŠΈλ‘œ μ„€μ •ν•œλ‹€. 차이점은 apply()κ°€ 두 번째둜 λ°›λŠ” νŒŒλΌλ―Έν„°κ°€ λ°°μ—΄μ΄λΌλŠ” 점이닀. ES6의 μ „κ°œμ—°μ‚°μžλ₯Ό μ‚¬μš©ν•˜λ©΄ 사싀 μ•„λž˜μ²˜λŸΌλ„ μ‚¬μš©ν•  수 μžˆλ‹€.

 

console.log(profile.call(user, ...arguments));
// Hannah is a JavaScript programmer, who lives in Seoul

bind()λŠ” μ¦‰μ‹œ μ‹€ν–‰λ˜μ§€ μ•ŠλŠ”λ‹€. μ•žμ„œ μ„€λͺ…ν•œ κ²ƒμ²˜λŸΌ λ°”μš΄λ“œλœ ν•¨μˆ˜κ°€ λ¦¬ν„΄λ˜μ–΄ λ‚˜μ€‘μ— 호좜된 λ•Œμ— λ°›μ•„μ˜€κ²Œ λœλ‹€. bind()λŠ” 첫 번째 νŒŒλΌλ―Έν„°λ‘œ λ°”μš΄λ“œλœ ν•¨μˆ˜κ°€ ν˜ΈμΆœλ˜λŠ” νƒ€κ²Ÿ ν•¨μˆ˜ λ‚΄ this μ»¨ν…μŠ€νŠΈλ₯Ό μ„€μ •ν•΄μ£ΌκΈ° μœ„ν•΄ μ‚¬μš©λœλ‹€.

const bound = profile.bind(user);
console.log(bound(...arguments)); // Hannah is a JavaScript programmer, who lives in Seoul

μœ„ μ½”λ“œμ—μ„œ λ³΄λŠ” κ²ƒμ²˜λŸΌ λ¨Όμ € μ»¨ν…μŠ€νŠΈλ₯Ό μ„€μ •ν•΄μ€€ ν•¨μˆ˜λ₯Ό λ§Œλ“€κ³ , λ‚˜μ€‘μ— ν•„μš”ν•  λ•Œ μƒˆλ‘œμš΄ νŒŒλΌλ―Έν„°μ™€ ν•¨κ»˜ ν˜ΈμΆœν•΄μ€€λ‹€.

 

ν™”μ‚΄ν‘œ ν•¨μˆ˜μ™€λŠ” μ•½κ°„μ˜ 차이가 μžˆμœΌλ‹ˆ μ•Œμ•„λ‘λ©΄ μ’‹λ‹€. bind(this)λ₯Ό μ‚¬μš©ν•  λ•ŒλŠ” ν•¨μˆ˜μ˜ ν•œμ •λœ 버전을 λ§Œλ“ λ‹€λ©΄, ν™”μ‚΄ν‘œ ν•¨μˆ˜λŠ” 아무것도 λ°”μΈλ”©ν•˜μ§€ μ•Šκ³  단지 thisλ₯Ό 갖지 μ•Šμ„ 뿐이닀. κ·Έλž˜μ„œ μ™ΈλΆ€μ—μ„œ thisλ₯Ό μ°ΎλŠ”λ‹€.

 

Reference

practical application of apply, call, and bind
arrow function