How to make proxy object in ES6?

code proxy object

Proxy is JS objects which can redirect itself to some other object. How does it work? Well. Let's create normal object first with some properties.

const obj = { 
    a: 10, 
    b: 20 
}; 
 

output:


Now we'll create empty proxy which will wrap this object. First parameter is target object, second parameter is handler (we put empty object there for now)

const obj = { 
    a: 10, 
    b: 20 
}; 
 
const proxy = new Proxy(obj, {}); 
 

output:


We write console.log. Notice that this proxy doesn't do anything for now and just returns original value.

const obj = { 
    a: 10, 
    b: 20 
}; 
 
const proxy = new Proxy(obj, {}); 
 
console.log(proxy.a); 
 

output:

10

Now we write `get` method in proxy handler. Now run program. It should write `13` because now proxy handles takes original value and adds 3 to it.

const obj = { 
    a: 10, 
    b: 20 
}; 
 
const proxy = new Proxy(obj, {}); 
const proxy = new Proxy(obj, { 
    get(obj, prop) { 
        return obj[prop] + 3; 
}); 
 
console.log(proxy.a); 
 

output:

13

That's all, folks! For questions you can write me here: https://twitter.com/hex13code