Почему моя ловушка для функции снятия денег не работает?
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);
пока все хорошо: checkAccount - это дерьмо, как я ожидал,
// 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.