left-icon

ECMAScript 6 Succinctly®
by Matthew Duffield

Previous
Chapter

of
A
A
A

CHAPTER 15

Proxies

Proxies


Proxies enable the creation of objects with the full range of behaviors available to host objects. They can be used for interception, object virtualization, logging, profiling, and more. Proxies are considered a meta programming feature.

Note: This is one of the areas where not all browsers or implementations are equal. The following examples can be run and tested under the latest version of Firefox or possibly Microsoft Edge.

Proxying

Consider the following example of proxying a normal object:

Code Listing: 206

var target = {};

var handler = {

  get: function (receiver, name) {

    return `Hello, ${name}!`;

  }

};

var p = new Proxy(target, handler);

p.world === 'Hello, world!';

     

As you can see from the preceding code, our target is a simple object literal. We perform a proxy on getters where it intercepts the get and returns the string Hello, plus the name of the property. We also test to see if the world property is the same as the string, Hello, world!.

Let’s also look at proxying a function object:

Code Listing: 207

var target = function () { return 'I am the target'; };

var handler = {

  apply: function (receiver, ...args) {

    return 'I am the proxy';

  }

};

var p = new Proxy(target, handler);

p() === 'I am the proxy';

     

This is very similar to the previous example with the exception that our target is now a function. You will notice that the handler takes in a receiver as well as a spread operator () to handle for any number of arguments.

Proxy traps

Proxy traps enable you to intercept and customize operations performed on objects. The following is a list of the traps available for all of the runtime-level meta-operations:

  • get
  • set
  • has
  • deleteProperty
  • apply
  • construct
  • getOwnPropertyDescriptor
  • defineProperty
  • getPropertyOf
  • setPropertyOf
  • enumerate
  • ownKeys
  • preventExtensions
  • isExtensible
Scroll To Top
Disclaimer
DISCLAIMER: Web reader is currently in beta. Please report any issues through our support system. PDF and Kindle format files are also available for download.

Previous

Next



You are one step away from downloading ebooks from the Succinctly® series premier collection!
A confirmation has been sent to your email address. Please check and confirm your email subscription to complete the download.