๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๐Ÿ“ฐ ์–ธ์–ด/JS - ๋น„๊ธฐ๋„ˆ ํŽธ

ํ•จ์ˆ˜ ํ”„๋กœํผํ‹ฐ - call, apply/ bind

MDN_Function.prototype.call() >

MDN_Function.prototype.apply() >

MDN_Function.prototype.bind() >

 

1. call() : ํ•จ์ˆ˜ ํ˜ธ์ถœ

์ฃผ์–ด์ง„ this ๊ฐ’ ๋ฐ ๊ฐ๊ฐ ์ „๋‹ฌ๋œ ์ธ์ˆ˜์™€ ํ•จ๊ป˜ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•œ๋‹ค.

function getTotal(one, two){
    return one + two;
}
let result = getTotal.call(this, 10, 20);
log(result);  //30

call() ๋ฉ”์†Œ๋“œ์˜ ์ฒซ ๋ฒˆ์งธ ํŒŒ๋ผ๋ฏธํ„ฐ์—๋Š” ํ˜ธ์ถœ๋œ ํ•จ์ˆ˜์—์„œ this๋กœ ์ฐธ์กฐํ•  ์˜ค๋ธŒ์ ํŠธ๋ฅผ ์ž‘์„ฑํ•œ๋‹ค. ์ผ๋ฐ˜์ ์œผ๋กœ this๋ฅผ ์‚ฌ์šฉํ•˜์ง€๋งŒ, ๋‹ค๋ฅธ ์˜ค๋ธŒ์ ํŠธ๋กœ๋„ ์ž‘์„ฑ์ด ๊ฐ€๋Šฅํ•˜๋‹ค.

let value = {one: 10, two: 20};
function getTotal(){
    return this.one + this.two;
}
let result = getTotal.call(value);
log(result);  //30

 

2. apply() : ํ•จ์ˆ˜ ํ˜ธ์ถœ, ๋ฐฐ์—ด์„ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ์‚ฌ์šฉ

์ฃผ์–ด์ง„ this ๊ฐ’๊ณผ ๋ฐฐ์—ด(๋˜๋Š” ์œ ์‚ฌ ๋ฐฐ์—ด ๊ฐ์ฒด)๋กœ ์ œ๊ณต๋˜๋Š” arguments๋กœ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•œ๋‹ค.

  • call()์€ ํ•จ์ˆ˜์— ์ „๋‹ฌ๋  ์ธ์ˆ˜๋ฆฌ์ŠคํŠธ๋ฅผ ๋ฐ›์ง€๋งŒ, apply()๋Š” ์ธ์ˆ˜๋“ค์˜ ๋‹จ์ผ ๋ฐฐ์—ด์„ ๋ฐ›๋Š”๋‹ค.
  • ํŒŒ๋ผ๋ฏธํ„ฐ ์ˆ˜๊ฐ€ ์œ ๋™์ ์ผ ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค.
function getTotal(one, two){
    return one + two;
}
let result = getTotal.appply(this, [10, 20]);
log(result);  //30

 

3. bind() : ์ƒˆ๋กœ์šด ์˜ค๋ธŒ์ ํŠธ๋ฅผ ์ƒ์„ฑํ•˜๊ณ  ํ•จ์ˆ˜ ์‹คํ–‰

bind() ๋ฉ”์†Œ๋“œ๊ฐ€ ํ˜ธ์ถœ๋˜๋ฉด ์ƒˆ๋กœ์šด ํ•จ์ˆ˜๋ฅผ ์ƒ์„ฑํ•œ๋‹ค. ๋ฐ›๊ฒŒ๋˜๋Š” ์ฒซ ์ธ์ž์˜ ๊ฐ’์œผ๋กœ๋Š” thisํ‚ค์›Œ๋“œ๋ฅผ ์„ค์ •ํ•˜๊ณ , ๋‹ค์Œ ์ธ์ž๋“ค์€ ๋ฐ”์ธ๋“œ๋œ ํ•จ์ˆ˜์˜ ์ธ์ˆ˜์— ์ œ๊ณต๋œ๋‹ค.

let value = {one: 10, two: 20};
function getTotal(){
    return this.one + this.two;
}

//getTotal์ด ์ทจ์ง€์— ๋งž๊ฒŒ ๋‹ฌ๋ผ์ง„ ์ƒˆ๋กœ์šด ValueTotalํ•จ์ˆ˜ ์ƒ์„ฑ
let ValueTotal = getTotal.bind(value); 
console.log(ValueTotal)  // 30

 

 

 

 

 

 

'๐Ÿ“ฐ ์–ธ์–ด > JS - ๋น„๊ธฐ๋„ˆ ํŽธ' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

ES6 - class  (0) 2021.05.25
for()๊ณผ forEach()  (0) 2021.05.24
์˜ค๋ธŒ์ ํŠธ ํ”„๋กœํ† ํƒ€์ž…  (0) 2021.05.23
new ์—ฐ์‚ฐ์ž  (0) 2021.05.17
๋ฐ์ดํ„ฐ ํƒ€์ž…  (0) 2021.05.17