Function.prototype.bind๋ ์๋ฐ์คํฌ๋ฆฝํธ์์ ํจ์๋ฅผ ์์ฑํ๊ณ ํธ์ถํ ๋ this ํค์๋์ ๊ฐ์ ๊ณ ์ ์ํค๋ ๋ฉ์๋์ด๋ค.
์ด ๋ฉ์๋๋ฅผ ์ฌ์ฉํ๋ฉด ํจ์๋ฅผ ํธ์ถํ ๋ ํจ์ ๋ด๋ถ์์ ์ฌ์ฉ๋๋ this๊ฐ ํน์ ํ ๊ฐ์ฒด๋ก ๊ณ ์ ๋๋ค.
ํจ์ ๋ฉ์๋ call, apply, bind๊ฐ ๊ณตํต์ ์ผ๋ก ์ฒซ๋ฒ์งธ ๋งค๊ฐ ๋ณ์๋ฅผ this ๊ฐ์ผ๋ก ์ง์ ํ ์ ์๋ค.
์ด ๋ฉ์๋๋ฅผ ์ฌ์ฉํ๋ฉด ํจ์๋ฅผ ํธ์ถํ ๋ ํจ์ ๋ด๋ถ์์ ์ฌ์ฉ๋๋ this๊ฐ ํน์ ํ ๊ฐ์ฒด๋ก ๊ณ ์ ๋๋ค.
ํจ์ ๋ฉ์๋ call, apply, bind๊ฐ ๊ณตํต์ ์ผ๋ก ์ฒซ๋ฒ์งธ ๋งค๊ฐ ๋ณ์๋ฅผ this ๊ฐ์ผ๋ก ์ง์ ํ ์ ์๋ค.
function greet() { console.log(`Hello, ${this.name}!`); } const person = { name: 'Alice' }; greet.call(person); // "Hello, Alice!" greet.apply(person); // "Hello, Alice!"
์ ์ฝ๋์์ call๊ณผ apply๋ฅผ ์ฌ์ฉํ์ฌ greet ํจ์๋ฅผ ํธ์ถํ ๋, this๋ person ๊ฐ์ฒด๋ฅผ ๊ฐ๋ฆฌ์ผ this๊ฐ์ ๋ช
์์ ์ผ๋ก ์ง์ ํด ์ฃผ์๋ค. ๋จ, bind๋ call, apply์ ๋ฌ๋ฆฌ ์๋ก์ด ํจ์๋ฅผ ๋ฐํํ๋ค๋ ํน์ง์ด ์๋ค. ์๋๋ bind๋ฅผ ์ฌ์ฉํ ์์ ์ด๋ค.
const module = { x: 42, getX: function() { return this.x; } }; const unboundGetX = module.getX; console.log(unboundGetX()); // undefined
์ฝ๋์์ module ๊ฐ์ฒด์๋ x๋ผ๋ ์์ฑ๊ณผ getX๋ผ๋ ๋ฉ์๋๊ฐ ์๋ค.
unboundGetX๋ getX ๋ฉ์๋๋ฅผ ๊ฐ๋ฆฌํค๋๋ฐ ์ด๋ this๋ ํธ์ถ ์์ ์ ๋ฐ๋ผ ๊ฒฐ์ ๋๋ค. ๊ทธ๋ฌ๋ฏ๋ก unboundGetX()๋ฅผ ํธ์ถํ๋ฉด this๋ ์ ์ญ๊ฐ์ฒด๋ฅผ ๊ฐ๋ฆฌํค๋ฏ๋ก x๋ ์ ์๋์ง ์์ ๊ฒ์ผ๋ก ์ทจ๊ธ๋์ด undefined๋ฅผ ๋ฐํํ๋ค.
์ด๋ฒ์๋ bind ๋ฉ์๋๋ฅผ ์ฌ์ฉํ ์์ ๋ฅผ ๋ณด๋๋ก ํ์.
const module = { x: 42, getX: function() { return this.x; } }; const unboundGetX = module.getX; const boundGetX = unboundGetX.bind(module); console.log(boundGetX()); // 42
์์์ unboundGetX ํจ์๋ฅผ module ๊ฐ์ฒด์ ๋ฐ์ธ๋ฉํ์ฌ boundGetX๋ฅผ ์์ฑํ๋ค.
์ด์ boundGetX()๋ฅผ ํธ์ถํ๋ฉด this๋ module ๊ฐ์ฒด๋ฅผ ๊ฐ๋ฆฌํค๋ฏ๋ก x์ ๊ฐ์ธ 42๋ฅผ ๋ฐํํ๋ค.
bind๋ฅผ ์ฌ์ฉํ๋ฉด ํจ์์ this๋ฅผ ๋ช
์์ ์ผ๋ก ์ง์ ํ ์ ์์ด์, ํจ์๋ฅผ ๋ค๋ฅธ ์ปจํ
์คํธ์์ ํธ์ถํ ๋ ์ ์ฉํ๋ค. ๋ํ ๋งค๊ฐ๋ณ์๋ฅผ ๋ฏธ๋ฆฌ ์ง์ ํ์ฌ ๋ถ๋ถ์ ์ผ๋ก ํจ์๋ฅผ ์คํํ๋ ๊ฒ๋ ๊ฐ๋ฅํ๋ค.