๐ย Reference
๐ย Chapter
โฃ
this ํค์๋๋ฅผ ๋ช
์์ ์ผ๋ก ์ค์ ํ๊ธฐ ์ํด ์ฌ์ฉํ๋ ๋ฉ์๋bind๋ ํจ์๋ฅผ ์ฆ์ ์คํํ์ง ์๊ณ , this๊ฐ ๋ฐ์ธ๋ฉ๋ ์๋ก์ด ํจ์๋ฅผ ๋ฐํํ๋ค. ๋์ค์ ํ์ํ ๋ ํธ์ถํ๊ฑฐ๋ ์ด๋ฒคํธ ๋ฆฌ์ค๋์์ ์์ฃผ ์ฌ์ฉํ๋ค.const newFunc = func.bind(thisArg)
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