HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

An Introduction to JavaScript Proxy

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptproxyintroduction

Problem

The JavaScript Proxy object is a relatively new addition to the language, having been introduced in ES6. It's based on the software design pattern of the same name, which creates a wrapper for another object, intercepting and redefining fundamental operations for that object.
A Proxy object is defined as follows:
The target is the object that the proxy wraps around, while the handler is an object that contains one or more "traps" - functions that intercept operations performed on the target object.
There are a variety of available traps that can be used to customize the behavior of the target object. Here's a brief overview of all available traps and what each one does:
  • get(target, prop, receiver) - Intercepts calls to target[prop].

Solution

const proxy = new Proxy(target, handler);


The target is the object that the proxy wraps around, while the handler is an object that contains one or more "traps" - functions that intercept operations performed on the target object.
There are a variety of available traps that can be used to customize the behavior of the target object. Here's a brief overview of all available traps and what each one does:
  • get(target, prop, receiver) - Intercepts calls to target[prop].
  • set(target, prop, value, receiver) - Intercepts calls to target[prop] = value.
  • has(target, prop) - Intercepts calls to prop in target.
  • apply(target, thisArg, argumentsList) - Intercepts calls to functions.

Code Snippets

const proxy = new Proxy(target, handler);
const targetObj = { name: 'John', age: 30 };

const handler = {
  get(target, property) {
    return property in target ? target[property] : null;
  }
};

const proxyObj = new Proxy(targetObj, handler);

proxyObj.name; // 'John'
proxyObj.age; // 30
proxyObj.address; // null

Context

From 30-seconds-of-code: proxy-introduction

Revisions (0)

No revisions yet.