call() - 매개변수를 직접 받음
const mike = {
name: "Mike"
}
const Tom = {
name: "Tom"
}
function showThisName() {
console.log(this.name);
}
showThisName(); // 아무 결과도 업음
showThisName.call(mike); // this가 mike가 되면서 this.name 결과, "Mike"
function update(birthYear, occupation) {
this.birthYear = birthYear;
this.occupation= occupation;
}
update.call(mike, 1999, "singer");
console.log(mike); // mike 객체가 업데이트 됨 결과, {"name": "Mike","birthYear": 1999,"occupation": "singer"}
apply() - 매개변수를 배열로 받음
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); // mike 객체가 업데이트 됨 결과, {"name": "Mike","birthYear": 1999,"occupation": "singer"}
bind - 함수의 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); // updateMike는 this의 값을 영구히 mike로 바꿈 결과, {"name": "Mike","birthYear": 1980,"occupation": "police"}
'Dev > JAVASCRIPT' 카테고리의 다른 글
Javascript JS 클래스(class) (1) | 2024.01.31 |
---|---|
Javascript JS 상속, 프로토타입(prototype) (0) | 2024.01.31 |
Javascript JS setTimeout / setInterval (0) | 2024.01.30 |
Javascript JS arguments, 나머지 매개변수, 전개 구문(Rest parameters, Spread syntax) (0) | 2024.01.30 |
Javascript JS 배열 구조 분해, 객체 구조 분해 (1) | 2024.01.30 |