2025. 8. 17. 02:55ใFront-end/JavaScript

๋ชฉ์ฐจ
1. ํจ์ ๋ด์ฅ ๋ฉ์๋
2. call(), apply()
2-1. call() ๋ฉ์๋
2-2. apply() ๋ฉ์๋
3. bind()
1. ํจ์ ๋ด์ฅ ๋ฉ์๋
์๋ฐ์คํฌ๋ฆฝํธ์ ํจ์๋ ์ผ๊ธ ๊ฐ์ฒด(First-class Object)๋ก, ํ๋กํผํฐ์ ๋ฉ์๋๋ฅผ ๊ฐ์ง ์ ์๋ค.
์ด ์ค ํจ์ ๊ฐ์ฒด์ ๊ธฐ๋ณธ์ ์ผ๋ก ์ ๊ณต๋๋ ๋ฉ์๋๋ค๋ค์ ํจ์ ๋ด์ฅ ๋ฉ์๋๋ผ๊ณ ํ๋ค.
์ฌ๋ฌ๊ฐ์ง ํจ์ ๋ด์ฅ ๋ฉ์๋๋ค์ด ์์ง๋ง ์ฃผ์ ํจ์ ๋ด์ฅ ๋ฉ์๋ ๋ช ๊ฐ์ง๋ง ๋ค๋ค๋ณด์.
2. call(), apply()
call()๊ณผ apply() ๋ฉ์๋๋ ์ด๋ค ํจ์(๊ฐ์ฒด)๋ฅผ ๋ค๋ฅธ ๊ฐ์ฒด์ ๋ฉ์๋์ฒ๋ผ ํธ์ถํ ์ ์๊ฒํ๋ค.
๋ ๋ฉ์๋์ ์ฐจ์ด์ ์ ๋๊ฒจ๋ฐ๋ ์ธ์์ ํ์์ด๋ค.
1. call() ๋ฉ์๋
ํน์ ๊ฐ์ฒด๋ฅผ this๋ก ๋ฐ์ธ๋ฉํ์ฌ, ํจ์๋ฅผ ์ฆ์ ์คํํ๋ค.
// 1. obj ๊ฐ์ฒด๋ฅผ call()๋ฉ์๋์ ์ฒซ๋ฒ์งธ ์ธ์๋ก ๋๊ฒจ this๋ก ๋ฐ์ธ๋ฉ
const obj = {name: 'Bang'};
function greeting() {
return `Hello ${this.name}`;
}
console.log(greeting.call(obj)); // 'Hello Bang'
// 2. ํธ์ถํ๋ ํจ์๋ก ์ธ์๋ฅผ ์ ๋ฌ
const obj = {name: 'Bang'};
function getUserInfo(age, country) {
return `name: ${this.name}, age: ${age}, country: ${country}`;
}
console.log(getUserInfo.call(obj, 26, 'Korea')); // name: Bang, age: 26, country: Korea'
2. apply() ๋ฉ์๋
call() ๋ฉ์๋์ ๋์ผํ์ง๋ง ์ ๋ฌํ ์ธ์๋ค์ ๋ฐฐ์ด ํํ๋ก ์ ๋ฌํด์ผ ํ๋ค.
const obj = {name: 'Bang'};
function getUserInfo(age, country) {
return `name: ${this.name), age: ${age}, country: ${country}`;
}
console.log(getUserInfo.apply(obj, [26, 'Korea'])); // 'name: Bang, age: 26, country: Korea'
3. bind()
ํจ์์ this ๋ฐ์ธ๋ฉ์ ์๊ตฌ์ ์ผ๋ก ๋ณ๊ฒฝํ๋ค.(์์ฑ์ ํจ์๋ก ์ฌ์ฉ๋๋ ๊ฒฝ์ฐ๋ ์์ธ)
bind() ๋ฉ์๋๋ก this๊ฐ ๋ณ๊ฒฝ๋ ํจ์๋ call(), apply(), ๋ ๋ค๋ฅธ bind() ๋ฉ์๋๋ก ๋ณ๊ฒฝํ ์ ์๋ค.
this๋ฅผ ๋ฐ์ธ๋ฉํ์ฌ ํจ์๋ฅผ ํธ์ถํ๋ ๊ฒ์ด ์๋๋ผ ์๋ก์ด ํจ์๋ฅผ ๋ฐํํ๋ค.
const obj1 = {name: 'Bang'};
const obj2 = {name: 'Kim' };
function getUserInfo(age, country) {
return `name: ${this.name}, age: ${age}, country: ${country}`;
}
const bound = getUserInfo.bind(obj1);
console.log(bound(26, 'Korea')); // 'name: Bang, age: 26, country: Korea'
console.log(bound.apply(obj2, [22, 'Korea'])); // 'name: Bang, age: 22, country: Korea'
bound ๋ณ์์์ bind(obj1)๋ก ์ธํด this๊ฐ์ด obj1๋ก ์๊ตฌ ๊ณ ์ ๋์๊ธฐ ๋๋ฌธ์ apply๋ฅผ ์ฌ์ฉํด๋ this ๊ฐ์ด obj1๋ก ๊ณ ์ ๋ ๊ฒ์ ํ์ธํ ์ ์๋ค.
์ฐธ๊ณ
'Front-end > JavaScript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| B12 : ๊ฐ์ฒด (0) | 2025.08.19 |
|---|---|
| ํธ๋์คํ์ผ๋ฌ์ ํด๋ฆฌํ (2) | 2025.08.19 |
| B10 : ํจ์์ this ํค์๋ (8) | 2025.08.16 |
| B9 : ํจ์์ ํจ์์ ์ ์ธ (6) | 2025.08.15 |
| B8 : ๋ฐ๋ณต๋ฌธ (2) | 2025.08.14 |
GitHub