问题描述
var target = { },
handler = {apply:()=> 42}
proxy = new Proxy(target,handler);
因此,Proxy对象应该被调用。但是,它不起作用:
proxy(); // TypeError:proxy不是一个函数
为什么?
根据它应该工作:
但是,有一个问题:并不是所有的Proxy对象都有[[Call]]方法:
因此,目标必须是一个函数对象:
var target =()=> {},
handler = {apply:()=> 42}
proxy = new Proxy(target,handler);
proxy(); // 42
请注意,我定义了 target
使用箭头函数来创建不是构造函数的函数对象。这种方式可以调用Proxy对象,但不能实例化。
如果你想添加一个构造陷阱,那么目标必须有一个[[Construct]]方法,所以用函数声明或函数表达式定义它。
I created a Proxy object with an "apply" trap:
var target = {},
handler = { apply: () => 42 }
proxy = new Proxy(target, handler);
Therefore, the Proxy object should be callable. However, it doesn't work:
proxy(); // TypeError: proxy is not a function
Why?
According to the definition of the [[Call]] internal method of Proxy objects it should work:
However, there is a problem: not all Proxy objects have the [[Call]] method:
Therefore, the target must be a function object:
var target = () => {},
handler = { apply: () => 42 }
proxy = new Proxy(target, handler);
proxy(); // 42
Note that I defined target
using an arrow function in order to create a function object which is not a constructor function. This way the Proxy object can be called but not instantiated.
If you want to add a "construct" trap too, the target must have a [[Construct]] method, so define it with a function declaration or function expression.
这篇关于不能设置“应用”陷阱到Proxy对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!