1. call()
call()
은 실행되는 함수의 this
값을 원하는 객체로 바꿔서 실행할 수 있게 해준다.
- 함수도 객체이며, 모든 함수는 call이라는 메소드를 가지고 있다.
함수.call(객체)
라 하면 '함수'라는 객체를 실행시키는 것
- 여기서 '객체'가 실행되는 함수의
this
를 대체한다.
const kim = {
name: 'kim',
first: 10,
second: 20
}
const lee = {
name: 'lee',
first: 10,
second: 10
}
function sum() {
return this.first + this.second;
}
console.log(sum.call(kim));
console.log(sum.call(lee));
2. bind
bind
는 실행되는 함수의 this
값을 원하는 객체로 고정시키는 새로운 함수를 만들어낸다.
- 기존의 함수에는 영향을 주지 않고 새로운 함수를 만들어내는 것이 포인트!
- this의 값을 영구적으로 바꾸는 함수를 만들어낸다.
const kim = {
name: 'kim',
first: 10,
second: 20
}
const lee = {
name: 'lee',
first: 10,
second: 10
}
function sum() {
return this.first + this.second;
}
const kimSum = sum.bind(kim);
console.log(kimSum());