@jgCarroll/

withdrawFromAccount

JavaScript

A common interview question.

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const account1 = {
  name: 'Jen',
  totalAmount: 5000,
  deductAmount: function(amount) {
    this.totalAmount -= amount;
    return 'Amount in account: ' + this.totalAmount;
  },
};
 
const account2 = {
  name: 'James',
  totalAmount: 8000,
};
 
const withdrawFromAccount = function(amount) {
  return account1.deductAmount.bind(account2, amount);
};
 
console.log(withdrawFromAccount(500)()); // logs: Amount in account: 7500
console.log(withdrawFromAccount(200)()); // logs: Amount in account: 7300

// check out questions regarding the bind() method.
Native Browser JavaScript