
๋ชจ๋ ํจ์์์ ์ฌ์ฉํ ์ ์์ผ๋ฉฐ, this๋ฅผ ํน์ ๊ฐ์ผ๋ก ์ง์ ํ ์ ์์ต๋๋ค.
const mike = {
name: "Mike",
};
const tom = {
name: "Tom",
};
function showThisName(){
console.log(this.name);
}
showThisName() // ์ฌ๊ธฐ์ this๋ window์ด๋ฏ๋ก, ์๋ฌด๊ฒ๋ ์ ๋ธ
showThisName.call(mike); //Mike
//์ฌ๊ธฐ์ this๊ฐ mike๊ฐ ๋ ๊ฒ
- ํจ์๋ฅผ ํธ์ถํ๋ฉด์ call์ ์ฌ์ฉํ๊ณ , this๋ก ์ฌ์ฉํ ๊ฐ์ฒด๋ฅผ ๋๊ธฐ๋ฉด,
ํด๋น ํจ์๊ฐ ์ฃผ์ด์ง ๊ฐ์ฒด์ method์ธ ๊ฒ์ฒ๋ผ ์ฌ์ฉํ ์ ์์- call์ ์ฒซ๋ฒ์งธ ๋งค๊ฐ๋ณ์๋ this๋ก ์ฌ์ฉ๋ ๊ฐ์ด๊ณ ,
๋งค๊ฐ ๋ณ์๊ฐ ๋ ์์ผ๋ฉด ๋งค๊ฐ๋ณ์๋ฅผ ํธ์ถํ๋ ํจ์๋ก ์ ๋ฌ ๋จ.
const mike = {
name: "Mike",
};
const tom = {
name: "Tom",
};
function showThisName(){
console.log(this.name);
}
function upDate(birthYear, occupation){
this.birthYear = birthYear;
this.occupation = occupation;
};
upDate.call(mike, 1992, 'programmer');
console.log(mike);
//{ name: "Mike", birthYear: 1992, occupation: 'programmer'}
//์ฒซ๋ฒ์งธ ๋งค๊ฐ๋ณ์: this ๊ฐ, ๋๋ฒ์งธ ๋งค๊ฐ ๋ณ์: ํจ์๊ฐ ์ฌ์ฉํ ๋งค๊ฐ๋ณ์๋ค์ ์์๋๋ก ์ ์ ๊ฒ.
ํจ์ ๋งค๊ฐ๋ณ์๋ฅผ ์ฒ๋ฆฌํ๋ ๋ฐฉ๋ฒ์ ์ ์ธํ๋ฉด, call๊ณผ ์์ ํ ๊ฐ์ต๋๋ค.
call์ ์ผ๋ฐ์ ์ธ ํจ์์ ๋ง์ฐฌ๊ฐ์ง๋ก ๋งค๊ฐ๋ณ์๋ฅผ ์ง์ ๋ฐ์ง๋ง,
apply๋ ๋งค๊ฐ๋ณ์๋ฅผ ๋ฐฐ์ด๋ก ๋ฐ์ต๋๋ค.
const mike = {
name: "Mike",
};
const tom = {
name: "Tom",
};
function showThisName(){
console.log(this.name);
}
function upDate(birthYear, occupation){
this.birthYear = birthYear;
this.occupation = occupation;
};
upDate.apply(mike, [1992, 'programmer']);
console.log(mike);
//{ name: "Mike", birthYear: 1992, occupation: 'programmer'}
apply๋ ๋ฐฐ์ด ์์๋ฅผ ํจ์ ๋งค๊ฐ๋ณ์๋ก ์ฌ์ฉํ ๋ ์ ์ฉํจ!
apply๋ ๋ฐฐ์ด์ ์ ๋ฌํ๋ฉด ๊ทธ ์ธ์๋ฅผ ์ฐจ๋ก๋๋ก ๋งค๊ฐ๋ณ์๋ก ์ฌ์ฉ
const nums = [3,10,1,6,4];
const minNum = Math.min(...nums);
const minNum = Math.min.call(null, ...nums);
const minNum = Math.min.apply(null, nums); //1
ํจ์์ this๊ฐ์ ์๊ตฌํ ๋ฐ๊ฟ ์ ์์ต๋๋ค.
const mike = {
name: "Mike",
};
function upDate(birthYear, occupation){
this.birthYear = birthYear;
this.occupation = occupation;
};
//ํญ์ this ๊ฐ์ด mike๊ฐ ๋๊ฒ ํด๋ณด์!
const updateMike = update.bind(mike);
//์ด ํจ์๋ ํญ์ ํญ์ this๋ฅผ mike๋ก ์ฌ์ฉํ๊ฒ ํจ
const user = {
name: "Mike",
showName: function() {
console.log(`hello, ${this.name}`);
},
};
user.showName();
let fn = user.showName;
fn(); //์ด๋ ์๋ฌด๊ฒ๋ ๋์ค์ง ์์, this๋ฅผ ์์ด๋ฒ๋ฆฐ ๊ฒ.
fn.call(user); //this๋ฅผ ์ฌ์ฉํ user๋ฅผ ๋ฃ์ด์ค, ์๋์ด!
fn.apply(user);
let boundFn =fn.bind(user);
boundFn(); //hello, Mike ์ ๋์ด!