The difference between call apply bind - Lee-hyuna/33-js-concepts-kr GitHub Wiki

์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ๋Š” ๋‹ค์ด๋‚˜๋ฏนํ•œ ์–ธ์–ด์ž…๋‹ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ์—ฌ๋Ÿฌ๊ฐ€์ง€ ์ž‘์—…์„ ํ•  ์ˆ˜ ์žˆ๋Š” ๊ฐ€๋ณ€์ ์ธ ์–ธ์–ด์ž…๋‹ˆ๋‹ค. ๊ฐ์ฒด ๋˜๋Š” ํด๋ž˜์Šค๊ฐ€ ์ƒ์œ„๋กœ๋ถ€ํ„ฐ ์ƒ์†๋ฐ›์„ ์ˆ˜ ์žˆ๋Š” ์–ธ์–ด์ด๋ฉฐ, ์ด ์ž‘์—…์€ call, apply, bind ์„ธ๊ฐ€์ง€ ๋ฐฉ๋ฒ• ์ค‘ ํ•˜๋‚˜๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

๊ทธ๋Ÿผ, ๋ญ๊ฐ€ ๋‹ค๋ฅธ์ง€ ์•Œ์•„๋ณผ๊นŒ์š”?

Call

์˜ˆ๋ฅผ ๋“ค์–ด, ์šฐ๋ฆฌ๋Š” obj๋ผ๊ณ  ๋ถˆ๋ฆฌ๋Š” ๊ฐ์ฒด๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. things๋ผ๋Š” key์— ๊ฐ’์ด 3์ด ๋“ค์–ด๊ฐ€์žˆ๋Š” ์˜ค๋ธŒ์ ํŠธ๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ์ด ๊ฐ์ œ์™€๋Š” ๋ฌด๊ด€ํ•œ addThings๋ผ๋Š” function์„ ๋งŒ๋“ค์–ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

let obj = {things: 3};
let addThings = function(a, b, c){
 return this.things + a + b + c;
};

์—ฌ๊ธฐ์„œ this.things๋Š” ๋ฌด์—‡์ผ๊นŒ์š”, addThings๋ฅผ ํ˜ธ์ถœํ•  ๋•Œ์—” things๋ผ๋Š” ๊ฒƒ์ด ์—†๋Š”๋ฐ ์™œ return๊ฐ’์— ๋„ฃ์—ˆ์„๊นŒ์š”? ์ด ๊ตฌ๋ฌธ์€ ์ž ์‹œ ๋„˜์–ด๊ฐˆ ํ•„์š”๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค. call์„ ์ด์šฉํ•˜์—ฌ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์ฝ”๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์œ„์˜ ์ฝ”๋“œ๋Š” ์‚ฌ์šฉ๊ฐ€๋Šฅํ•œ ์ฝ”๋“œ๊ฐ€ ๋˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค

console.log( addThings.call(obj, 1,4,6) )

return๊ฐ’์œผ๋กœ ์ˆซ์ž 14๊ฐ€ ๋‚˜์™”์Šต๋‹ˆ๋‹ค.

๊ทธ๋Ÿผ ์ฒซ๋ฒˆ์งธ parmeter๋ฅผ call๋กœ ๋ฐ›์•˜์„ ๊ฒฝ์šฐ ์œ„์˜ obj๋ฅผ ๋„˜๊ฒผ์„ ๋•Œ this๋Š” ๋ฌด์—‡์„ ์œ„ํ•ด ์žˆ๋Š” ๊ฑธ๊นŒ์š”? things ์ž์ฒด์˜ ๊ฐ’์„ ์ธ์ž๊ฐ’์œผ๋กœ ๋„˜๊ฒผ๊ธฐ ๋•Œ๋ฌธ์— ํ•ด๋‹น ๊ตฌ๋ฌธ์„ ํ†ต๊ณผํ•œ ๊ฒƒ์ž…๋‹ˆ๋‹ค.

return this.things + a + b + c;

์ด ๊ตฌ๋ฌธ์„ ํ’€์–ด์“ฐ์ž๋ฉด ์•„๋ž˜์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค.

return 3 + 1 + 4 + 6

๊ทธ๋ž˜์„œ return ๊ฐ’์€ 14๊ฐ€ ๋œ ๊ฒƒ ์ž…๋‹ˆ๋‹ค. ์ด์ œ call์€ ๋๋‚ฌ์Šต๋‹ˆ๋‹ค! apply๋กœ ๋„˜์–ด๊ฐ€๋ณด์ฃ 

Apply

apply๋Š” call๊ณผ ๋น„์Šทํ•ฉ๋‹ˆ๋‹ค.

๊ฐ€์žฅ ํฐ ์ฐจ์ด์ ์€ ์šฐ๋ฆฌ๊ฐ€ arguments๋ฅผ ํ†ต๊ณผํ•  ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•์ž…๋‹ˆ๋‹ค. ์šฐ๋ฆฌ๋Š” ๊ทธ๊ฒƒ๋“ค์„ ๋ฐฐ์—ด๋กœ ์ „๋‹ฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ด์ „ ์ฝ”๋“œ๋ฅผ ์‚ญ์ œํ•˜๊ณ  ๋‹ค์‹œ ์‹œ์ž‘ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.

let obj = {things: 3};

let addThings = function(a, b, c){
 return this.things + a + b + c;
};
let arr = [1,4,6];
console.log( addThings.apply(obj, arr) );

Bind

let obj = {things: 3};
let addThings = function(a, b, c){
 return this.things + a + b + c;
};

console.log( addThings.bind(obj, 1,4,6) );

bind๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ์ง„ํ–‰ํ–ˆ๋‹ค๋ฉด 14๋ผ๊ณ  ๋œจ์ง€ ์•Š์„ ๊ฒƒ ์ž…๋‹ˆ๋‹ค. bind๋Š” function์˜ ๋ณต์‚ฌ๋ณธ์„ return ํ•˜์ง€๋งŒ ๋‹ค๋ฅธ ์ปจํ…์ŠคํŠธ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ž‘๋™ํ•ฉ๋‹ˆ๋‹ค. ์œ„์˜ ์ฝ”๋“œ์—์„œ๋Š” obj๋ฅผ ํ†ต๊ณผ์‹œ์ผฐ์ง€๋งŒ ์‹คํ–‰ํ•˜์ง€๋Š” ์•Š์Šต๋‹ˆ๋‹ค.

console.log( addThings.bind(obj, 1,4,6)() );

bind๋ฅผ ํ†ตํ•˜์—ฌ obj์˜ this๋ฅผ ์ „๋‹ฌ ํ•ด์ค€ ํ›„ ๊ทธ ๋‹ค์Œ ์ธ์ž๋“ค์„ ์ „๋‹ฌํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

console.log( addThings.bind(obj)(1,4,6) );

์ด์ œ ์ ์šฉ์ด ๋˜์—ˆ์–ด์š”! ์ž˜ ์‹คํ–‰์ด ๋˜์ฃ ?

Call / Apply / Bind์— ๋Œ€ํ•ด ์•Œ์•„๋ณด๋Š” ์‹œ๊ฐ„์ด์—ˆ์Šต๋‹ˆ๋‹ค!

Happy coding.