call, apply, bind
์๋ฐ์คํฌ๋ฆฝํธ์์์ ํจ์ ํธ์ถ ๋ฐฉ์
function add(a: number, b: number): number {
return a + b;
}
console.log(add(10, 20));
console.log(add.apply(null, [10, 20]));
console.log(add.call(null, 10, 20));
console.log(add.bind(null, 10, 20)());
call, apply, bind : ํจ์ ํธ์ถ ๋ฐฉ์๊ณผ ๊ด๊ณ์์ด this๋ฅผ ์ง์ ํ ์ ์์
javascript์ ํจ์๋ ๊ฐ์ ์์ ๋ง์ this๋ผ๋ ๊ฒ์ ์ ์ํ๋ค.
๊ธฐ๋ณธ์ ์ผ๋ก this๋ window์ด์ง๋ง this๋ ๊ฐ์ฒด ๋ด๋ถ, ๊ฐ์ฒด ๋ฉ์๋ ํธ์ถ์, ์์ฑ์ new ํธ์ถ์, ๋ช ์์ bind์์ ๋ฐ๋ผ ๋ฐ๋๋ค.
์๋ฐ์คํฌ๋ฆฝํธ์์๋ ํจ์๋ฅผ ์ด๋์ ์ด๋ป๊ฒ ํธ์ถํ๋๋์ ๊ด๊ณ์์ด this๊ฐ ๋ฌด์์ธ์ง ์ง์ ํ ์ ์๋ค.
call, apply, bind ๋ ํจ์์ this๋ฅผ ๋ช ์์ ์ผ๋ก ๋ฐ์ธ๋ฉ ํ ๋ ์ฌ์ฉํฉ๋๋ค.
์ ์ฉํ๋ฉด์ ์์ฃผ ์ฌ์ฉ๋๋ ํจ์์ด๊ณ , ํํ๋ ์กฐ๊ธ์ฉ ๋ค๋ฅด๋ ์ต์ํด ์ง๋๋ก ํ์
const mike = {
name: "Mike",
};
const tom = {
name: "Tom",
};
function showThisName() {
console.log(this.name);
}
function updateBtith(birthYear, occupation) {
this.birthYear = birthYear;
this.occupation = occupation;
}
showThisName.call(mike);
showThisName.call(tom);
updateBtith.call(mike, 1999, "singer");
console.log(mike);
updateBtith.apply(tom, [1995, "programmer"]);
console.log(tom);

const nums = [3, 100, 12, 342, 2];
const minNum = Math.min(...nums);
const maxNum = Math.max(...nums);
console.log(minNum); //2
console.log(maxNum); //342
apply ์์ฉํด๋ณด๊ธฐ
const nums = [3, 100, 12, 342, 2];
//const minNum = Math.min(...nums);
const minNum = Math.min.apply(null, nums);
//const maxNum = Math.max(...nums);
const maxNum = Math.max.apply(null, nums);
console.log(minNum); //2
console.log(maxNum); //342
call ์์ฉํด๋ณด๊ธฐ
const nums = [3, 100, 12, 342, 2];
//const minNum = Math.min(...nums);
//const minNum = Math.min.apply(null, nums);
const minNum = Math.min.call(null, ...nums);
//const maxNum = Math.max(...nums);
//const maxNum = Math.max.apply(null, nums);
const maxNum = Math.max.call(null, ...nums);
console.log(minNum); //2
console.log(maxNum); //342
๊ฒฐ๊ตญ ์ค์ํ ๊ฒ์
apply์ call์ ๋์ ๋ฐฉ์์ ๊ฐ์๋ฐ ๋งค๊ฐ ๋ณ์๋ฅผ ๋ฐ๋ ๋ฐฉ๋ฒ๋ง ๋ค๋ฅผ ๋ฟ์ด๋ค.
bind
bindํจ์๊ฐ call, apply์ ๋ค๋ฅธ ์ ์ ํจ์๋ฅผ ์คํํ์ง ์๋๋ค๋ ์ ์ด๋ค. ๋์ boundํจ์๋ฅผ ๋ฆฌํดํ๋ค.
const mimi = {
name: "MiMi",
};
function update(birthYear, occupation) {
this.birthYear = birthYear;
this.occupation = occupation;
}
const updateMiMi = update.bind(mimi);
updateMiMi(1995, "artist");
console.log(mimi);

const user = {
name: "Kara",
lookName: function () {
console.log(`hello, ${this.name}`);
},
};
user.lookName(); //hello, Kara
let fn = user.lookName;
fn.call(user); //hello, Kara
fn.apply(user); //hello, Kara
let boundFn = fn.bind(user);
boundFn(); //hello, Kara
์ ์ฉ ์ฌ๋ก
const say = function() {
console.log(this); // ์ฌ๊ธฐ์ this๋ ๋ญ๊น?
console.log("Hello, my name is " + this.name);
};
say();
sayํจ์์์ Window๊ฐ์ฒด๋ฅผ ์ฌ์ฉํ๊ณ ์ถ์ง ์๋ค. ์ฆ, this๋ฅผ ๊ทธ๋ ๊ทธ๋ ์๋ง์ ๊ฐ์ฒด๋ก ๋ฐ๊ฟ์ this๊ฐ์ ๋ฐ๋ผ ์ธ์ฌ๋ง์ด ํ ์ ์๋๋ก ๋ง๋ค๊ธฐ ์ํด์ this๋ฅผ bindingํ ์ ์๋ค. ๋ช ์์ ์ผ๋ก ์์ this๋ฅผ Window๊ฐ ์๋ ๋ค๋ฅธ ๊ฐ์ฒด๋ก ๋ฐ๊ฟ์ฃผ๋ ํจ์๊ฐ call, apply, bind์ด๋ค.