Summary: in this tutorial, you will learn about the JavaScript Proxy object in ES6.
What is a JavaScript Proxy object
A JavaScript Proxy is an object that wraps another object (target) and intercepts the fundamental operations of the target object.
The fundamental operations can be the property lookup, assignment, enumeration, function invocations, etc.
Creating a proxy object
To create a new proxy object, you use the following syntax:
let proxy = new Proxy(target, handler);
Code language: JavaScript (javascript)In this syntax:
target– is an object to wrap.handler– is an object that contains methods to control the behaviors of thetarget. The methods inside thehandlerobject are called traps.
A simple proxy example
First, define an object called user:
const user = {
firstName: 'John',
lastName: 'Doe',
email: '[email protected]',
}
Code language: JavaScript (javascript)Second, define a handler object:
const handler = {
get(target, property) {
console.log(`Property ${property} has been read.`);
return target[property];
}
}
Code language: JavaScript (javascript)Third, create a proxy object:
const proxyUser = new Proxy(user, handler);
Code language: JavaScript (javascript)The proxyUser object uses the user object to store data. The proxyUser can access all properties of the user object.