假设我们有一个对象: 和带有“异步陷阱”的代理: 我已经在上面尝试了代码,但是没有用。 似乎Proxy无法将异步获取识别为陷阱,也不会拦截获取器。 如何解决? 要么: 是否有另一种方法可以在不更改原始对象的情况下获得对象属性的“延迟”值? ...
提示:本站收集StackOverFlow近2千万问答,支持中英文搜索,鼠标放在语句上弹窗显示对应的参考中文或英文, 本站还提供 中文繁体 英文版本 中英对照 版本,有任何建议请联系yoyou2525@163.com。
为什么我的提现功能陷阱不起作用?
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.