JavaScript Proxy

This tutorial will cover the basics of JavaScript Proxy, a powerful new feature in ES6 (ES2015). JavaScript Proxy is a feature that allows you to intercept and customize operations performed on objects. It provides a way to intercept and customize operations such as getting and setting properties, deleting properties, enumerating properties, and so on.

Why should you use it?

  • It provides a way to intercept and customize operations on objects.
  • It can be used to create custom data structures and classes.
  • It can be used to create custom APIs with custom behavior.

Proxy

The Proxy object is used to define custom behavior for fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc).

A Proxy is created with two parameters: a target object and a handler object. The target object is the object which the proxy virtualizes. The handler object is an object which contains traps. A trap is a method that provides custom behavior for fundamental operations.

Here is an example of a Proxy object:

const person = {
  name: 'John Doe'
};

const handler = {
  get(target, prop) {
    if (prop === 'name') {
      return 'Mr. ' + target[prop];
    }
    return target[prop];
  }
};

const proxy = new Proxy(person, handler);

The handler object has a get trap which is used to define custom behavior for property lookup. In this example, the get trap returns a modified version of the name property.

Here is an example of using the Proxy object:

const person = {
  name: 'John Doe'
};

const handler = {
  get(target, prop) {
    console.log('Accessing property ' + prop);
    return target[prop];
  }
};

const proxy = new Proxy(person, handler);

proxy.name;

In this example, the get trap is used to log a message when the name property is accessed.

Proxies can also be used to define custom behavior for function invocation. Here is an example of using a Proxy to define custom behavior for function invocation:

const person = {
  name: 'John Doe',
  sayHello() {
    return 'Hello, my name is ' + this.name;
  }
};

const handler = {
  apply(target, thisArg, args) {
    console.log('Calling function ' + target.name);
    return target.apply(thisArg, args);
  }
};

const proxy = new Proxy(person.sayHello, handler);

proxy();

In this example, the apply trap is used to log a message when the sayHello function is called.

Proxies can be used to define custom behavior for a variety of operations, such as property lookup, assignment, enumeration, and function invocation. They are a powerful tool for modifying the behavior of objects.

1