本文介绍了为什么在Node中没有调用我的功能代理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好地使用了代理 get 方法.然后,我尝试在函数上使用它,并很快意识到我需要使用 apply 方法.这个简单的例子不起作用.它永远不会进入申请.

I was using proxy get method fine. Then I tried using it on a function and quickly realized I needed to use the apply method. This simple example is not working. It never enters apply.

Node希望支持应用 https://node.green/#ES2015-built-ins-Proxy--apply--handler .不知道我在做什么错.

Node looks to support apply https://node.green/#ES2015-built-ins-Proxy--apply--handler. Not sure what I'm doing wrong.

var Foo = {
  runme: function() {
    return 1;
  }
};

var Magic = {
  Foo: Foo
};

Magic.Foo = new Proxy(Object.assign({}, Magic.Foo), {
  apply: function(target, thisArg, argumentsList) {
    // never gets in here
    console.log('Proxying function call');
    console.log(target);
    return 2;
  }
});

console.log(Foo.runme()); // outputs 1
console.log(Magic.Foo.runme()); // outputs 1

我直接在 Magic.foo 上并通过 Object.assign 尝试了Proxy,以查看是否需要将其作为自己的对象.都不起作用.

I tried both Proxy on Magic.foo directly and via the Object.assign to see if it needed to be its own object or not. Neither worked.

推荐答案

您在这里假定 apply 陷阱的工作方式与 get 陷阱相同-即,对于代理对象-但他们没有.当代理本身称为函数时, apply 陷阱运行.在这里,您的代理服务器是 Magic.Foo ,但是您永远不会调用 Magic.Foo().您只能调用 Magic.Foo.runme(),它不是代理函数.

You assume here that apply traps work like get traps -- i.e., for any property of the proxied object -- but they do not. The apply trap runs when the Proxy itself is called a function. Here, your proxy is Magic.Foo, but you never call Magic.Foo(). You only call Magic.Foo.runme(), which is not a proxied function.

您必须将要拦截其调用的每个函数包装在其自己的 Proxy 包装器中.

You must wrap each function whose invocation you wish to intercept in its own individual Proxy wrapper.

或者,您可以在 Magic.Foo 上使用 get 陷阱,该陷阱将为每个访问的属性返回具有适当行为的函数.

Alternatively, you could use a get trap on Magic.Foo that returns a function with the appropriate behavior for each accessed property.

这篇关于为什么在Node中没有调用我的功能代理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 11:50