함수 호출 방식과 관계없이 this 를 지정할 수 있게 해주는 메소드이다.
자세한 설명은 각설하고 예제를 통해 이해하는 것이 가장 직관적이다.
1. call()
const mike = {
name : "Mike"
};
const tom = {
name : "Tom"
};
function showThisName(){
console.log(this.name);
}
showThisName.call(mike); // Mike
showThisName.call(tom); // Tom
위와 같이 call을 통해 함수와 연결시켜서 오브젝트 필드(프로퍼티) 를 활용할 수 있다.
2. apply()
일반적으로 call 과 동일한 역할을 한다고 이해하면된다. Input Parameter 의 차이만 존재하는데 예제를 확인해보자.
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, [1999, "singer"]);
console.log(mike);
update.apply(tom, [2002, "teacher"]);
console.log(tom);
위 예제에서 볼 수 있듯이 배열 형태로 Input parameters 를 전달하는 것이다.
참고로 아래와 같이 사용할 수도 있다.
const nums = [3,4,5,6];
const minNum = Math.min.apply(null, nums);
const minNum2 = Math.min.call(null, ...nums);
console.log(minNum);
console.log(minNum2);
3. bind()
const mike = {
name : "mike"
};
function update(birthyear, occupation){
this.birthYear = birthyear;
this.occupatiopn = occupation;
}
const updateMike = update.bind(mike);
updateMike(1994, "shwan");
console.log(mike);
추가로 fat arrow function 이라는 것이 존재하는데 예제는 다음과 같다
// normal version
const normalFunction = (function (){
//do something...
}).bind(this);
// Fat Arrow function
const arrowFunction = () => {
//do something..
}
위 두가지 버전은 동일한 역할을 한다고 이해하면 된다.
ES16에서 추가된 문법이며 실제로 CoffeeScript에서는 => 를 활용하는 Fat Arrow function 과 -> 를 활용하는 Thin Arrow function이 존재했다고 하는데, 여기서 => 만 추가로 사용 가능하게 되었다고 한다는 후문이다.
무분별한 Fat Arrow function의 경우 사용하지 않는 Input parameter를 연결하는 느낌을 주는데(개인적으로) 무조건적으로 사용하는 것 보다는 차라리 명시적으로 bind를 해주는 것이 오히려 좋지 않을까? 하는 개인 적인 생각이 있다.