일반적인 방법
function 함수(){
return console.log('호출해줭')
}
함수();
메서드를 사용하는 방법
const sum = (a, b, c) => {
return a + b + c;
}
sum.apply(null, [10, 20, 30]);
sum.call(null, 10, 20, 30);
매개변수로 this와 배열(또는 유사배열)을 받고 함수를 호출한다.
sum.apply(null, [10, 20, 30]);
매개변수로 this와 값들을 받고 함수를 호출한다.
sum.call(null, 10, 20, 30);
apply, call, bind 메서드에 매개변수 this를 지정하여 변경할 수 있다.
const person = {
name: '임아무개',
getName: function() {
console.log(this.name);
}
}
const btob = {
name: '이창섭'
}
person.getName(); // 임아무개
person.getName.apply(btob); // 이창섭
person.getName.call(btob); // 이창섭
함수가 가리키는 this를 바꿔준다. 호출은 하지 않고 함수만 반환한다.
let leechangsub = person.getName.bind(btob); // this만 바뀜
leechangsub(); // 따로 호출해야함
화살표 함수 사용하면 안돼요
const person = {
name: '임아무개',
getName: () => {
console.log(this.name);
}
}
person.getName(); //
화살표 함수는 호출되는 시점에 상위 환경 this를 참조하기 때문에
전역객체를 가리키게 되어 값이 없다고 나온다.