자바스크립트에서는 함수 호출 방식과 관계없이 this를 지정할 수 있다.
call
모든 함수에서 사용할 수 있으며, this를 특정 값으로 지정할 수 있다.
함수명.call(this로 사용할 객체, 함수에 전달할 파라미터...)
const mike = {
name: "Mike",
};
const tom = {
name: "Tom",
};
function showThisName() {
console.log(this.name); // window.name
}
function update(birthYear, occupation) {
this.birthYear = birthYear;
this.occupation = occupation;
};
showThisName(); // 빈 문자열
//함수명.call(this로 사용할 객체, 함수에 전달할 파라미터...)
showThisName.call(mike); // Mike
showThisName.call(tom); // Tom
update.call(mike, 1999, "singer");
console.log(mike); // name: "Mike", birthYear: 1999, occupation: "singer"
update.call(tom, 2002, "teacher");
console.log(tom); // name: "Tom", birthYear: 2002, occupation: "teacher"
- showThisName(): this.name을 콘솔창에 출력하는 함수
- update(): this의 속성을 전달받은 파라미터로 변경하는 함수
apply
함수 매개변수를 처리하는 방법을 제외하면 call과 완전히 같다.
call은 일반적인 함수와 마찬가지로 매개변수를 직접 받지만 apply는 매개변수를 배열로 받는다.
함수명.apply(this로 사용할 객체, [함수에 전달할 파라미터...])
const mike = {
name: "Mike",
};
const tom = {
name: "Tom",
};
function update(birthYear, occupation) {
this.birthYear = birthYear;
this.occupation = occupation;
};
update.apply(mike, [1999, "singer"]);
console.log(mike); // name: "Mike", birthYear: 1999, occupation: "singer"
update.apply(tom, [2002, "teacher"]);
console.log(tom); // name: "Tom", birthYear: 2002, occupation: "teacher"
- apply는 함수의 파라미터를 배열로 받을 때 유용하다.
- 매개변수를 배열로 넘기면 차례대로 인수로 사용한다.
const nums = [3, 10, 1, 6, 4];
//const maxNum = Math.max(...nums); // spread 연산자 사용
const maxNum = Math.max.call(null, ...nums); // Math.max.call(null, 3, 10, 1, 6, 4)
const minNum = Math.min.apply(null, nums); // Math.min.apply(null, [3, 10, 1, 6, 4])
bind
함수의 this 값을 영구히 바꾼다.
함수명.bind(this로 고정할 객체, 고정할 파라미터...) 는 this와 파라미터가 고정된 함수를 반환한다.
const mike = {
name: "Mike",
};
const tom = {
name: "Tom",
};
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"
updateMike.call(tom);
updateMike(1988, "cook");
console.log(tom); // name: "Tom"
console.log(mike); // name: "Mike", birthYear: 1988, occupation: "cook"
- 이미 this에 mike가 할당된 updateMike에 call을 호출하여 this를 tom으로 바꾸려고 해도 바꿀 수 없다.
- 여전히 mike에 대한 update가 이루어진다.
const user = {
name: "Mike",
showName: function() {
console.log(`Hello, ${this.name}`);
},
};
user.showName(); // Hello, Mike
let fn = user.showName; // fn에 showName 함수를 할당할 때 this를 잃는다.
fn(); // Hello,
fn.call(user); // Hello, Mike
fn.apply(user); // Hello, Mike
let boundFn = fn.bind(user); // user.showName.bind(user)
boundFn(); // Hello, Mike
- 객체 함수가 객체 내부가 아닌 다른 곳에 전달하면 this 정보(context)를 잃는다.
- boundFn은 this가 user로 고정된 showName 함수이다.
function mul(a, b) {
return a * b;
}
let double = mul.bind(null, 2); // a를 2로 고정
// double에 고정된 a를 제외한 b만을 전달한다.
console.log(double(3)); // mul(2, 3) = 6
console.log(double(4)); // mul(2, 4) = 8
console.log( ouble(5)); // mul(2, 5) = 10
bindAll
객체 내 복수의 함수를 바인딩
for (let key in user) {
if (typeof user[key] == 'function') {
user[key] = user[key].bind(user);
}
}
'Advance II > JavaScript' 카테고리의 다른 글
| [JS] JavaScript Algorithms and Data Structures (0) | 2023.01.30 |
|---|