1

为什么我的取款陷阱功能不起作用?

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);

到目前为止一切顺利:checkingAccount 就像我预期的那样是个废话

// 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 

这里我有一个问题。似乎正在执行的方法是 accountChecking.withdraw ,当它尝试更新基金时,会触发基金财产的陷阱。

safeCheckingAccount.withdraw(10000); // this is raising an error different from expected.
4

0 回答 0