๐Ÿ“’ Function.prototype.apply/call/bind ๋ฉ”์„œ๋“œ์— ์˜ํ•œ ๊ฐ„์ ‘ ํ˜ธ์ถœ

zooyahoยท2022๋…„ 8์›” 3์ผ
0
post-thumbnail

Function.prototype.apply/call/bind ๋ฉ”์„œ๋“œ์— ์˜ํ•œ ๊ฐ„์ ‘ ํ˜ธ์ถœ

์ด๋“ค ๋ฉ”์„œ๋“œ๋Š” ๋ชจ๋“  ํ•จ์ˆ˜๊ฐ€ ์ƒ์†๋ฐ›์•„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

โ— apply/call ๋ฉ”์„œ๋“œ

๐Ÿ“Ž Function.prototype.apply(thisArg[, argsArray])

: ์ฃผ์–ด์ง„ this ๋ฐ”์ธ๋”ฉ๊ณผ ์ธ์ˆ˜ ๋ฆฌ์ŠคํŠธ ๋ฐฐ์—ด์„ ์‚ฌ์šฉํ•˜์—ฌ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•œ๋‹ค.

  • thisArg: this๋กœ ์‚ฌ์šฉํ•  ๊ฐ์ฒด
  • argsArray: ํ•จ์ˆ˜์— ์ „๋‹ฌํ•  ์ธ์ˆ˜ ๋ฆฌ์ŠคํŠธ์˜ ๋ฐฐ์—ด ๋˜๋Š” ์œ ์‚ฌ๋ฐฐ์—ด ๊ฐ์ฒด

๐Ÿ“Ž Function.prototype.call(thisArg[, arg1[, arg2[, ...]]])

: ์ฃผ์–ด์ง„ this ๋ฐ”์ธ๋”ฉ๊ณผ ,๋กœ ๊ตฌ๋ถ„๋œ ์ธ์ˆ˜ ๋ฆฌ์ŠคํŠธ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•œ๋‹ค.

  • thisArg: this๋กœ ์‚ฌ์šฉํ•  ๊ฐ์ฒด
  • argsArray: ํ•จ์ˆ˜์— ์ „๋‹ฌํ•  ์ธ์ˆ˜ ๋ฆฌ์ŠคํŠธ

๐Ÿ”ฅ apply์™€ call๋ฉ”์„œ๋“œ์˜ ๋ณธ์งˆ์ ์ธ ๊ธฐ๋Šฅ์€ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ๊ฒƒ์ด๋‹ค. ์ธ์ˆ˜๋ฅผ ์ „๋‹ฌํ•˜๋Š” ๋ฐฉ์‹๋งŒ ๋‹ค๋ฅผ ๋ฟ ๋™์ผํ•˜๊ฒŒ ๋™์ž‘ํ•จ.

๋Œ€ํ‘œ์  ์‚ฌ์šฉ

๐Ÿ˜ค arguments ๊ฐ์ฒด์™€ ๊ฐ™์€ ์œ ์‚ฌ ๋ฐฐ์—ด ๊ฐ์ฒด์— ๋ฐฐ์—ด ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒฝ์šฐ!!

๐Ÿ‘พ#์˜ˆ์ œ

function foo(){
  console.log(arguments); 
  
  const arr = Array.prototype.slice.call(arguments);
  // const arr = Array.prototype.slice.apply(arguments);
  console.log(arr);
  
  return arr;
}
foo(1,2,3); // [1,2,3]

โ— bind ๋ฉ”์„œ๋“œ

Function.prototype.bind(thisArg)

: apply์™€ call ๋ฉ”์„œ๋“œ์™€ ๋‹ค๋ฅด๊ฒŒ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•˜์ง€ ์•Š๋Š”๋‹ค.
: ์ฒซ ๋ฒˆ์งธ ์ธ์ˆ˜๋กœ ์ „๋‹ฌํ•œ ๊ฐ’์œผ๋กœ this ๋ฐ”์ธ๋”ฉ์ด ๊ต์ฒด๋œ ํ•จ์ˆ˜๋ฅผ ์ƒˆ๋กญ๊ฒŒ ์ƒ์„ฑํ•ด ๋ฐ˜ํ™˜ํ•œ๋‹ค!!

๐Ÿ‘พ#01

function foo(){
  return this;
}

// this๋กœ ์‚ฌ์šฉํ•  ๊ฐ์ฒด
const thisArg = { a:1 };

console.log(foo.bind(thisArg)); // foo
console.log(foo.bind(thisArg)()); // { a:1 }

๐Ÿ”ฅ bind ๋ฉ”์„œ๋“œ๋Š” ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•˜์ง€ ์•Š์œผ๋ฏ€๋กœ ๋ช…์‹œ์ ์œผ๋กœ ํ˜ธ์ถœํ•ด์•ผ ํ•จ.

๋Œ€ํ‘œ์  ์‚ฌ์šฉ

๐Ÿ˜ค ๋ฉ”์„œ๋“œ์˜ this์™€ ๋ฉ”์„œ๋“œ ๋‚ด๋ถ€์˜ ์ค‘์ฒฉ ํ•จ์ˆ˜ ๋˜๋Š” ์ฝœ๋ฐฑ ํ•จ์ˆ˜์˜ this๊ฐ€ ๋ถˆ์ผ์น˜ํ•˜๋Š” ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•ด ์‚ฌ์šฉํ•œ๋‹ค!!

๐Ÿ‘พ#02

const person = {
  name: 'lee',
  foo(callback) {
    // bind ๋ฉ”์„œ๋“œ๋กœ callback ํ•จ์ˆ˜ ๋‚ด๋ถ€์˜ this ๋ฐ”์ธ๋”ฉ์„ ์ „๋‹ฌ
    setTimeout(callback.bind(this), 100);
  }
}
person.foo(function() {
  console.log(`Hi! my name is ${this.name}.`); // Hi! my name is lee.
});
profile
์ฆ๊ฒ๊ฒŒ ๊ฐœ๋ฐœํ•˜์ž ์ฅฌ์•ผํ˜ธ๐Ÿ‘ป

0๊ฐœ์˜ ๋Œ“๊ธ€