The Proxy
object is used to wrap another object (target
) and defines handler
object to control the basic operations like reading and writing on the target
object by implementing the proxy object's internal methods
const targetObj = {
firstName: 'John',
lastName: 'Hendry'
}
const handlerObj = {}
const proxyObj = new Proxy(target, handlerObj)
The handler
object used to augment the implementation for one or more of the proxy object's internal methods. Some of the internal methods are set
, get
, has
, deleteProperty
and so on. To get the complete list to refer the below table link
https://tc39.es/ecma262/#table-30
Example - get metod
const target = {
firstName: 'John',
lastName: 'Hendry'
}
const handler = {
get(target, prop) {
if(prop === 'name' && !(prop in target)){
return `${target.firstName} ${target.lastName}`;
}
}
}
const proxy = new Proxy(target, handler)
target.name // undefined
proxy.name // "John Hendry"
Supported Internal Methods
| Internal Method | Handler Method |
|-----------------------|--------------------------|
| [[GetPrototypeOf]] | getPrototypeOf |
| [[SetPrototypeOf]] | setPrototypeOf |
| [[IsExtensible]] | isExtensible |
| [[PreventExtensions]] | preventExtensions |
| [[GetOwnProperty]] | getOwnPropertyDescriptor |
| [[DefineOwnProperty]] | defineProperty |
| [[HasProperty]] | has |
| [[Get]] | get |
| [[Set]] | set |
| [[Delete]] | deleteProperty |
| [[OwnPropertyKeys]] | ownKeys |
| [[Call]] | apply |
| [[Construct]] | construct |