如何实现不显眼的方法转发?
var o = new SomethingComplex;
var o.foo = new SomeThing; // we have o.foo.doSomething
setUpForwarding(o, o.foo);
o.doSomething(); // calls o.doSomething if exist, else o.foo.doSomething
如何设置不显眼的方法转发?使用 ES5 技术是完全没问题的。我可以想象这在 IE6 中是不可能的,
我不是在寻找像 o.call("doSomething");
这样的方法,我希望它完全不引人注目。
同时编辑 .__proto__
以便将 o.foo
扔到原型链中是作弊行为,也是不允许的。允许在其自然原型链中使用 o.foo
覆盖 o
,但 o
的复杂性不受限制。
还有可行的选择吗?
我只记得 node-proxy 的存在,它允许您扩展 node.js 实现代理(用 C++ 实现)。这提供了包罗万象的功能,并且可以移植到其他 SS JS。
var o = new SomethingComplex;
var o.foo = new SomeThing; // we have o.foo.doSomething
setUpForwarding(o, o.foo);
o.doSomething(); // calls o.doSomething if exist, else o.foo.doSomething
How would one go about setting up unobtrusive method forwarding? Using ES5 techniques is perfectly fine. I can imagine this being impossible in IE6
I'm not looking for a method like o.call("doSomething");
I want it to be completely unobtrusive.
Also editing .__proto__
so you can throw o.foo
in the prototype chain is cheating and is disallowed. Overwriting o
with o.foo
in it's natural prototype chain is allowed but o
is not limited in complexity.
Are there any viable options left?
I just remember the existance of node-proxy which allows you to extend node.js to implement proxies (Implemented in C++). This provides catch-all functionality and can probably be ported to other SS JS.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
JavaScript 没有“捕获所有”处理程序,尽管正在考虑将其用于未来版本。
您可以通过让
setUpForwarding
迭代foo
的所有函数成员来解决此特定问题,然后在o
中创建具有相同名称的转发函数。但这仅适用于函数。JavaScript does not have 'catch all' handlers, although it is under consideration for a future version.
You could solve this specific issue by having
setUpForwarding
iterate through all function member offoo
and then create a forwarding function ino
with the same name. This will only work for functions though.