简体   繁体   中英

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. Lets say I would like the proxy to print message "Calling [ methodname ] from object [ object ]"

Example:

obj.doSomething();

Output:

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

How to implement this in 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

You can use the builtin JavaScript Proxy object, like so:

 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

In ES5 it is more complicated, but you can do the following:

 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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