[문제 풀어보기] this bind

JBoB·2023년 2월 27일
0

this bind 을 공부하고 나서 문제를 풀어보았다.
console.log() 찍힌 값은 얼마인가?

const account1 = {
  name: 'Yohan',
  totalAmount: 5000,
  deductAmount: function(amount) {
    this.totalAmount -= amount;
    return 'Amount in account: ' + this.totalAmount;
  },
};
 
const account2 = {
  name: 'John',
  totalAmount: 8000,
};
 
const withdrawFromAccount = function(amount) {
  return account1.deductAmount.bind(account2, amount);
};
 
console.log(withdrawFromAccount(500)());
console.log(withdrawFromAccount(200)());

문제를 보고 진짜 내가 공부를 제대로 했나 싶을 정도였었다. 하지만 함수를 호출한 방법에 의해 결정된다는 걸 다시 생각하면서 풀었더니 감이 잡혀서 풀 수 있었다.

withdrawFromAccount 함수에서 account2는 this의 키워드로 쓰일것이다. 그러면 account1에 있는 yohan의 totalAmount는 훼이크라고 볼수 있다.
deductAmount 값에 John의 8000을 할당해주면

'Amount in account: 7500'
'Amount in account: 7300'
//7500에서 다시 그 값을 할당해 주기에 7300이 나온다.

이런 결과가 나온다!

profile
간절하고 치열하게 살자

0개의 댓글