【发布时间】:2017-02-22 01:23:34
【问题描述】:
var cache = new Proxy(new Map(), {
apply: function(target, thisArg, argumentsList) {
console.log('hello world!');
}
});
cache.set('foo', 'bar');
据我所知,应该导致hello world! 被记录到控制台并且地图的foo 键未设置。但是,当我运行它时,它会抛出:
TypeError: Method Map.prototype.set called on incompatible receiver [object Object]
at Proxy.set (native)
at repl:1:7
at ContextifyScript.Script.runInThisContext (vm.js:23:33)
at REPLServer.defaultEval (repl.js:340:29)
at bound (domain.js:280:14)
at REPLServer.runBound [as eval] (domain.js:293:12)
at REPLServer.onLine (repl.js:537:10)
at emitOne (events.js:101:20)
at REPLServer.emit (events.js:189:7)
at REPLServer.Interface._onLine (readline.js:238:10)
我已经在 Google 上搜索过所有 MDN 代理文档并浏览了好几次,但我无法理解为什么这不起作用。
有什么想法吗?我在 Node.js 7.5.0 上。
【问题讨论】:
-
您实际上想要完成什么?你能创建一个
Map的子类吗?例如,您可以在子类中覆盖.set()。 -
@jfriend00 是的,覆盖
.set是我最初的想法。我使用 Proxy 的唯一原因是因为这个项目具有教育意义,我想尝试新的闪亮 :D -
apply陷阱用于被调用的函数对象,并且永远不会对Map对象(不可调用)起作用。