๐Ÿ“Œ[JS] call, apply, bind ๋ฉ”์„œ๋“œ ์‚ฌ์šฉ๋ฒ•

hareยท2023๋…„ 1์›” 16์ผ
0

js-tips

๋ชฉ๋ก ๋ณด๊ธฐ
2/5

call

const mike = {
	name: "Mike";
}
 
function showThisName() {
	console.log(this.name);
}

function update(birthYear, occupation){
	this.birthYear = birthYear;
    this.occupation = occupation;
}

call ๋ฉ”์„œ๋“œ์˜ ์ฒซ ๋ฒˆ์งธ ๋งค๊ฐœ๋ณ€์ˆ˜ == this ๋กœ ์‚ฌ์šฉํ•  ๊ฐ’

showThisName.call(mike); // Mike
update.call(mike, 1996, "singer");
console.log(mike); //{name: "Mike", birthYear: 1996, occupation: "singer"}

apply

call๊ณผ ์‚ฌ์šฉ๋ฒ•์ด ๋น„์Šทํ•˜์ง€๋งŒ ํ•จ์ˆ˜ ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ๋ฐฐ์—ด๋กœ ๋ฐ›์Œ.
๋™์ž‘ ๋ฐฉ์‹์€ ๊ฐ™์Œ. ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ๋ฐ›๋Š” ๋ฐฉ๋ฒ•๋งŒ ๋‹ค๋ฆ„.

๋‹ค์Œ๊ณผ ๊ฐ™์ด ๋ฐฐ์—ด ํ˜•ํƒœ๋Š” ์Šคํ”„๋ ˆ๋“œ ์—ฐ์‚ฐ์ž๋ฅผ ์ด์šฉํ•ด ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ๋„ฃ์–ด์ค„ ์ˆ˜ ์žˆ์—ˆ๋‹ค.

const nums = [1,2,4,5,6,10];
const minNum = Math.min(...nums) // 1
const maxNum = Math.max(...nums) // 10

๋ฐฐ์—ด ๋งค๊ฐœ๋ณ€์ˆ˜๋Š” ์ฐจ๋ก€๋Œ€๋กœ ์ธ์ˆ˜๋กœ ์‚ฌ์šฉ๋จ

apply๋ฅผ ์‚ฌ์šฉํ•ด๋ณด์ž.

const nums = [1,2,4,5,6,10];
const minNum = Math.min.apply(null,nums) // 1
const maxNum = Math.max.apply(null,nums) // 10

Math.min, Math.max๋Š” this๊ฐ€ ํ•„์š”ํ•˜์ง€ ์•Š์•„ ์•„๋ฌด๊ฐ’์ด๋‚˜ ๋„ฃ์–ด์ฃผ์–ด๋„ ๋œ๋‹ค.

bind

this ๊ฐ’์„ ์˜๊ตฌ์ ์œผ๋กœ ๋ฐ”๊ฟ”์ค„ ์ˆ˜ ์žˆ๋‹ค.

const mike = {
	name: "Mike";
}

function update(birthYear, occupation){
	this.birthYear = birthYear;
    this.occupation = occupation;
}

const updateMike = update.bind(mike);

updateMike(1980, "police");
console.log(mike); // {name: "Mike", birthYear: 1980, occupation: "police"}

์˜ˆ์‹œ

const User = {
	name: "Mike",
    showName: function () {
     console.log(`hello, ${this.name}`);
     },
};

user.showName(); // hello, Mike

let fn = user.showName(); 

fn(); // hello, 

method - .์•ž์ด this!
this๋ฅผ ์žƒ์–ด๋ฒ„๋ ธ๊ธฐ ๋•Œ๋ฌธ์— name์ด ์ถœ๋ ฅ๋˜์ง€ ์•Š์Œ.

let boundFn = fn.bind(user);
boundFn(); // hello, Mike
profile
ํ•ด๋œฐ๋‚ 

0๊ฐœ์˜ ๋Œ“๊ธ€