简体   繁体   English

如何在 ES5 中实现代理

[英]How to implement Proxy in ES5

Lets have the following snippet:让我们有以下片段:

var obj = {};
obj.doSomething = function(){
    console.log("Hello from obj");
}

I would like to create a proxy for this object and each time any method from obj is called, to do something else and then call the actual obj method.我想为此 object 创建一个代理,并且每次调用来自obj的任何方法时,执行其他操作,然后调用实际的obj方法。 Lets say I would like the proxy to print message "Calling [ methodname ] from object [ object ]"假设我希望代理打印消息“从 object [ object ] 调用 [方法名称]”

Example:例子:

obj.doSomething();

Output: Output:

Calling [doSomething] method from object [obj].
Hello from obj

How to implement this in ES5 ?如何在ES5中实现这一点?

I suggest you to check this article about the try-catch proxy , modify the line before apply() with your own needs as well as syntax to ES5我建议你查看这篇关于 try-catch 代理的文章,根据你自己的需要修改apply()之前的行以及 ES5 的语法

You can use the builtin JavaScript Proxy object, like so:您可以使用内置的 JavaScript 代理 object,如下所示:

 var obj = {}; obj.doSomething = function(){ console.log("Hello from obj"); } const handler = { get: function(target, prop) { console.log(`Calling [${prop}] from object [${target}]`); target[prop](); } }; const proxy = new Proxy(obj, handler); proxy.doSomething

see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy请参阅: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

In ES5 it is more complicated, but you can do the following:在 ES5 中它更复杂,但您可以执行以下操作:

 var obj = {}; obj.doSomething = function(){ console.log("Hello from obj"); } function Proxy(target) { var handler = function(prop) { return function() { console.log("Calling [" + prop + "] from object [" + target + "]"); target[prop](); } } var p = {}; var keys = Object.keys(target); for(var i=0; i < keys.length; i++) { var key = keys[i]; p[key] = handler(key); } return p; } var proxy = new Proxy(obj); proxy.doSomething()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM