snippetjavascriptTip
An Introduction to JavaScript Proxy
Viewed 0 times
javascriptproxyintroduction
Problem
The JavaScript
A
The
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:
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 totarget[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 totarget[prop].set(target, prop, value, receiver)- Intercepts calls totarget[prop] = value.has(target, prop)- Intercepts calls toprop 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; // nullContext
From 30-seconds-of-code: proxy-introduction
Revisions (0)
No revisions yet.