1

Why my trap for withdraw function is not working?

const checkingAccount = {
    owner: 'Saulo',
    funds: 1500,
    withdraw: function(amount) {
      this.funds -= amount;
      console.log('withdraw ' + amount + '. Current funds:' + this.funds);
    },
    deposit: function(amount) {
      this.funds += amount;
      console.log('deposit ' + amount + '. Current funds:' + this.funds);
    }  
}

checkingAccount.withdraw(100);
checkingAccount.withdraw(2000);
checkingAccount.deposit(650);
checkingAccount.withdraw(2000);
checkingAccount.withdraw(2000);
checkingAccount.funds = 10000;
checkingAccount.withdraw(2000);

so far so good: the checkingAccount is a crap as I was expected to

// my proxy handler
const handler = {
  set: (target, prop, value) => {
    if (prop === 'funds') {
      throw 'funds cannot be changed.'
    }
    target[prop] = value;
    return true;
  },
  apply: (target, context, args) => {
    console.log('withdraw method should execute this console.log but it isn\'t.');
  },
  /* this is the function I want to use to replace original withdraw method
  withdraw: function(obj, amount) {
    console.log('hi');
    if (obj.funds - amount >= 0) {
      obj.withdraw(amount);
    } else {
      throw 'No funds available. Current funds: ' + obj.funds;
    }
  }
  */
};

const safeCheckingAccount = new Proxy(checkingAccount, handler);


// other properties still working properly
console.log(safeCheckingAccount.owner);
safeCheckingAccount.owner = 'Debora';
console.log(safeCheckingAccount.owner);

// Checking funds attempt to change will raise an exception. Super!
console.log(safeCheckingAccount.funds);
safeCheckingAccount.funds = 10000; // this will raise error. cannot change funds 

Here I have an issue. it seems the method is being executed is accountChecking.withdraw and when it tries to update the fund then the trap for fund property is fired.

safeCheckingAccount.withdraw(10000); // this is raising an error different from expected.
Saulo
  • 499
  • 1
  • 4
  • 16
  • 1
    `apply` happens on the `withdraw` function, not the `checkingAccount` object. – Patrick Roberts Oct 12 '18 at 16:24
  • Since `checkingAccount` is not a function, the `apply` trap has no meaning for it. – Bergi Oct 12 '18 at 16:29
  • could you help me with some example of how would it be correct? Because it is working properly for the attribute 'funds'. How would it be correct to intercept the call to withdraw function? – Saulo Oct 12 '18 at 16:30
  • 1
    You'll need to construct two proxies. One with a handler containing a `set` trap for the `checkingAccount`, and another containing an `apply` trap for `checkingAccount.withdraw` – Patrick Roberts Oct 12 '18 at 17:06

0 Answers0