๐ย Reference
๐ย Chapter
โฃ
bind()
๋ฉ์๋๋ ์ฃผ๋ก ํจ์ ํธ์ถ ์ this
์ ์ปจํ
์คํธ๋ฅผ ๊ณ ์ ํ๊ธฐ ์ํด ์ฌ์ฉ๋๋ค.this
์ ๊ฐ์ ํจ์๊ฐ ์ด๋ป๊ฒ ํธ์ถ๋๋์ง์ ๋ฐ๋ผ ๋์ ์ผ๋ก ๊ฒฐ์ ๋๊ธฐ ๋๋ฌธ์ ํผ๋์ ์ค ์ ์๋ค.bind()
๋ ์ด ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ์ฌ, ์ด๋ค ๋ฐฉ์์ผ๋ก ํจ์๋ฅผ ํธ์ถํ๋ this
๊ฐ ํญ์ ์ํ๋ ๊ฐ์ฒด๋ฅผ ๊ฐ๋ฆฌํค๋๋ก ๋ง๋ ๋ค.// ์๋ก์ด ํจ์ = ์๋ณธ ํจ์.bind(thisArg, arg1, arg2, ...)
const newFunc = originalFunc.bind(thisObject, 'value1', 'value2');
thisObject
: newFunc
์ด ํธ์ถ๋ ๋ this
๋ก ๋ฐ์ธ๋ฉ๋ ๊ฐ์ฒด์ด๋ค.arg1, arg2, ...
: ์๋ณธ ํจ์์ ์ ๋ฌํ ์ด๊ธฐ ์ธ์๋ค์ด๋ค. ์ด๋ ๋ถ๋ถ ์ ์ฉ ๊ธฐ๋ฒ์ ํด๋น๋๋ค.this ์ปจํ ์คํธ ๊ณ ์ ํ๊ธฐ
this
๊ฐ ๋ฐ๋๋ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๋ ๋ฐ ์ ์ฉํ๋ค.const user = {
name: 'John',
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
// setTimeout์ ์ฝ๋ฐฑ ํจ์๋ก user.greet๋ฅผ ์ง์ ์ ๋ฌํ๋ฉด
// 'this'๊ฐ ์ ์ญ ๊ฐ์ฒด(window)๋ฅผ ๊ฐ๋ฆฌ์ผ์ name์ ์ฐพ์ง ๋ชปํฉ๋๋ค.
setTimeout(user.greet, 1000); // ์ถ๋ ฅ: Hello, my name is undefined
// bind()๋ฅผ ์ฌ์ฉํ์ฌ 'this'๋ฅผ user ๊ฐ์ฒด๋ก ๊ณ ์
const boundGreet = user.greet.bind(user);
setTimeout(boundGreet, 1000); // ์ถ๋ ฅ: Hello, my name is John
๋ถ๋ถ ์ ์ฉ(Partial Application)
bind()
๋ ์ฒซ ๋ฒ์งธ ์ธ์๋ก this
๋ฅผ, ๊ทธ ์ดํ ์ธ์๋ก ํจ์์ ์ ๋ฌํ ๊ฐ์ ๋ฏธ๋ฆฌ ์ค์ ํ ์ ์์ต๋๋ค.function multiply(a, b) {
return a * b;
}
// this๋ null๋ก ๋ฌด์ํ๊ณ , ์ฒซ ๋ฒ์งธ ์ธ์(a)๋ฅผ 2๋ก ๊ณ ์
const double = multiply.bind(null, 2);
console.log(double(5)); // ์ถ๋ ฅ: 10