ES6 Proxy

Proxy

ES6 introduces Proxy. So what is Proxy?

Proxy, as the name suggests, acts as a proxy. In ES6, Proxy can intercept and customize operations performed on an object.

This means you can listen to and modify access and changes made to an object from the outside, and do additional things.

Here’s an example:

var obj={
  a:1
}
var proxyObj =  new Proxy(obj,{ //proxyObj will inherit obj
    set:function(){
      alert("I've been modified")
    }
  });

  // Modify property
  proxyObj.a=2; // After the property is modified, the previously set handler is triggered
  console.log(obj.a) // 2

It’s that simple.


Available Intercept Operations

1. get(target, propKey, receiver)

Intercepts property read operations, e.g., proxy.foo and proxy[‘foo’].

2. set(target, propKey, value, receiver)

Intercepts property setting operations, e.g., proxy.foo = v or proxy[‘foo’] = v. Returns a boolean.

3. has(target, propKey)

Intercepts the propKey in proxy operation and the hasOwnProperty method. Returns a boolean.

4. deleteProperty(target, propKey)

Intercepts the delete proxy[propKey] operation. Returns a boolean.

5. ownKeys(target)

Intercepts Object.getOwnPropertyNames(proxy), Object.getOwnPropertySymbols(proxy), and Object.keys(proxy). Returns an array. This method returns all of the object’s own properties, while Object.keys() only returns enumerable properties.

6. getOwnPropertyDescriptor(target, propKey)

Intercepts Object.getOwnPropertyDescriptor(proxy, propKey). Returns the property descriptor.

7. defineProperty(target, propKey, propDesc)

Intercepts Object.defineProperty(proxy, propKey, propDesc) and Object.defineProperties(proxy, propDescs). Returns a boolean.

8. preventExtensions(target)

Intercepts Object.preventExtensions(proxy). Returns a boolean.

9. getPrototypeOf(target)

Intercepts Object.getPrototypeOf(proxy). Returns an object.

10. isExtensible(target)

Intercepts Object.isExtensible(proxy). Returns a boolean.

11. setPrototypeOf(target, proto)

Intercepts Object.setPrototypeOf(proxy, proto). Returns a boolean.

If the target object is a function, two additional operations can be intercepted.

12. apply(target, object, args)

Intercepts the Proxy instance being called as a function, e.g., proxy(...args), proxy.call(object, ...args), proxy.apply(...).

13. construct(target, args)

Intercepts the Proxy instance being called as a constructor, e.g., new proxy(...args).

Article Link:

/en/archive/es6-proxy/

# Related Articles