如何使用代理申请陷阱?

时间:2018-10-12 16:22:19

标签: javascript proxy-pattern

为什么我的提款功能无法使用?

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.

0 个答案:

没有答案