Proxy handler method getOwnPropertyDescriptor() in Javascript
The Proxy handler getOwnPropertyDescriptor() is used to intercept object static method getOwnPropertyDescriptor(). It must returns an object or undefined which was returned by an Object static method getOwnPropertyDescriptor().
Syntax
 1 new Proxy(<target>, {
 2   getOwnPropertyDescriptor(<target>, <prop>) {
 3   }
 4 });
target : a target object to retrieve descriptor property
prop : a property name or Symbol to retrieve descriptor from target object
Proxy handler getOwnPropertyDescriptor()
 1 const object = {
 2   id: 1,
 3   name: 'javascript'
 4 };
 5 
 6 const handler = {
 7   getOwnPropertyDescriptor(target, prop) {
 8     return { configurable: true, enumerable: true, value: target[prop] };
 9   }
 10 };
 11 
 12 const pxy = new Proxy(object, handler);
 13 const descriptor = Object.getOwnPropertyDescriptor(pxy, 'id');
 14 console.log(descriptor);
In the above example, an object is define with properties and values and a handler object created by overriding getOwnPropertyDescriptor() method which returns the same value returned by Object static method.
An object of Proxy is created by passing an object and handler method. An Object.getOwnPropertyDescriptor() method called which was intercepted by pxy object method and returns the custom descriptor method as shown below.
Descriptor object
 1 {
 2    configurable: true,
 3    enumerable: true,
 4    value: 1,
 5    writable: false
 6 }

Proxy object inline handler

Proxy object inline handler
 1 let object = {id: 101, name: "JavaScript", version: 12.11};
 2 
 3 const proxy = new Proxy(object, {
 4     getOwnPropertyDescriptor(target, prop) {
 5         return { writable: true, configurable: true, enumerable: true, value: target[prop] };
 6     }
 7 });
 8 
 9 const descriptor = Object.getOwnPropertyDescriptor(proxy, 'name');
 10 console.log("Descriptor for name property :");
 11 console.log(descriptor);
In the above example, a proxy object created by specifying an object and handler with getOwnPropertyDescriptor() method that receives two parameters target object and name of property. An Object method getOwnPropertyDescriptor() method called by passing an object and name of property. It calls proxy object method getOwnPropertyDescriptor() that returns Descriptor object.
Output
 1 Descriptor for name property :
 2 {
 3   value: 'JavaScript',
 4   writable: true,
 5   enumerable: true,
 6   configurable: true
 7 }
Privacy Policy
Terms of Service
Disclaimer
Contact us
About us