
함수를 호출하는 방법에는 ()를 사용하거나 call이나 apply를 사용하는 방법이 있는데요!
웹브라우저에서 전역객체는 window인데요! 그래서 기본적으로 this는 window를 말합니다. 오늘은call과 apply 사용하여 this를 지정하여 사용하는 방법과 bind에 대해 정리해보려고 합니다.
call의 첫번째 인자를 설정하여 this를 지정하여 객체를 재할당 할 수 있습니다. 그리고 두번째 인자들은 옵션값으로 인수를 전달하여 함수를 호출할 수 있어요!
func.call(thisArg[, arg1[, arg2[, ...]]])
아래 코드는 call을 사용한 예제 코드입니다. call을 사용하여 첫번째 인자로 전달해준 me를 적용하여 this를 변경하여 줄 수 있어요!
const user = {
name: "happy",
age: 23,
sayHello: function () {
console.log(`Hello! my name is ${this.name}!`);
},
};
const me = {
name: "wooden",
age: 26,
};
user.sayHello();
user.sayHello.call(me);
apply는 argument와 같은 유사배열 형태로 인자를 전달한다는 점이 call과 다른점인데요! 아래와 같이max()를 예로 사용해볼 수 있습니다.
func.apply(thisArg, [argsArray])
const numArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
//Math.max(numArr); -> x
console.log(Math.max(...numArr)); // o
console.log(Math.max.apply(null, numArr)); // Math가 내장객체임으로 this x
마지막으로 bind를 사용해볼까요! bind는 call과 apply와 다르게 새로운 함수를 만들어 반환한다는 차이점이 있습니다.
func.bind(thisArg[, arg1[, arg2[, ...]]])
아래와 같이 bind를 사용하여 새로운 함수를 반환받아 introduce라는 이름으로 사용할 수 있습니다.
const user = {
name: "happy",
age: 23,
sayHello: function () {
console.log(`Hello! my name is ${this.name}!`);
},
};
const me = {
name: "wooden",
age: 26,
};
const introduce = user.sayHello.bind(me);
introduce();
이번에 다시 한번 공부해보면서 개념정리보다는 앞으로는 좀 더 응용해서 사용할 수 있도록 해야겠다는 생각을 하게되었어요! 다양하게 사용해보고 적용해보면서 좀 더 자유롭게 사용할 수 있도록!