๐ call, apply, bind: ํจ์ ํธ์ถ ๋ฐฉ์๊ณผ ๊ด๊ณ ์์ด this๋ฅผ ์ง์ ํ ์ ์๋ค.
const mike = {
name: โMikeโ
}
const tom = {
name: โTomโ
}
function showThisName () {
console.log(this.name);
}
showThisName(); // undefined
showThisName.call(mike); // โMikeโ
showThisName.call(tom); // โTomโ
showThisName()
์ ํธ์ถํ๋ฉด undefined
๋ฅผ ๋ฐํ.this
๋ฅผ ์ง์ ํด์ค์ผ ๊ธฐ๋ํ๋ ๊ฒฐ๊ณผ๊ฐ ๋์ด.call()
์ this
๋ก ์ง์ ๋ ๊ฐ์ฒด๋ฅผ ๋งค๊ฐ๋ณ์๋ก ๋ฐ๋ ํจ์.// this๊ฐ ๋ฐ๋ผ๋ณด๋ ๊ฐ์ฒด๋ ์ ์ฝ๋์ mike ๊ฐ์ฒด ์ฐธ์กฐ
function update(birth, job) {
this.birthday = birth;
this.job = job;
}
update.call(mike, 1989, โEnginnerโ); // { name: โMikeโ, birthday: 1989, job: โEnginnerโ }
call()
์ ์ฒซ ๋ฒ์งธ ๋งค๊ฐ๋ณ์๋ this๊ฐ ๋ ๊ฐ์ฒด์ด๋ค.1989
๊ฐ birth
๋ก, Enginner
๊ฐ job
์ผ๋ก// ์ ์ฝ๋์ mike ๊ฐ์ฒด์ update ํจ์ ์ฐธ์กฐ
update.apply(mike, [ 1989, โEnginnerโ ]); // { name: โMikeโ, birthday: 1989, job: โEnginnerโ }
apply()
๋ ๋งค๊ฐ๋ณ์๊ฐ ์๋ ๋ฐฐ์ด์ ํํ๋ก ํจ์์ ๋งค๊ฐ๋ณ์๋ฅผ ์ ๋ฌ.const nums = [2, 5, 1, 45, 13];
const numMin = Math.min(nums); // NaN
const numMax = Math.max(nums); // NaN
nums
๊ฐ ๋ฐฐ์ด์ด๊ธฐ ๋๋ฌธ์ ์๋ฃํ์ด ๋ง์ง์์ NaN
์ด ๋ฐํ.call()
๋ก ์ ๋ฌ ํ๊ธฐ ์ํด์๋ ์ ๊ฐ ๊ตฌ๋ฌธ ์ฌ์ฉ// ์ ๊ฐ ๊ตฌ๋ฌธ์ ํตํด ๊ฐ์ ํจ์์ ์ ๋ฌํ๊ธฐ
const nums = [2, 5, 1, 45, 13];
const numMin = Math.min(โฆnums); // 1
const numMax = Math.max(โฆnums); // 45
// apply ํจ์ ์ฌ์ฉํ๊ธฐ
const nums = [2, 5, 1, 45, 13];
const numMin = Math.min.apply(null, nums); // 1
const numMax = Math.max.apply(null, nums); // 45
apply()
๋ ๋ฐฐ์ด์์๋ฅผ ๋งค๊ฐ๋ณ์๋ก ์ ๋ฌํ๋ค.null
์ด ๋ค์ด๊ฐ๋ ์ด์ ๋ Math
๋ฅผ this
๋ก ์ ๋ฌํ ํ์๊ฐ ์๊ธฐ ๋๋ฌธ์ด๋ค.call()
,apply()
๋ชจ๋ ์ฒซ ๋ฒ์งธ ๋งค๊ฐ๋ณ์๋ this
๋ฅผ ์ง์ ํด์ฃผ๋ ์ญํ ์ด๋ค.(์์์ ์์๋ณด์๋ค)const user = {
name: โJaneโ,
showName: function () {
console.log(this.name);
}
}
user.showName(); // Jane
const fn = user.showName;
fn(); // undefined
fn
์ user.showName
์ ํ ๋นํ๋ฉด์ this
๋ฅผ ์์ด๋ฒ๋ฆผ.bind()
๋ก ํจ์์ this
๊ฐ์ user
๊ฐ์ฒด๋ฅผ ์๊ตฌํ ๋ฐ๋ผ๋ณด๊ฒ ํ ์ ์๋ค.
const user = {
name: โJaneโ,
showName: function () {
console.log(this.name);
}
}
let fn = user.showName();
let boundFn = fn.bind(user);
boundFn(); // Jane