Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptExplain handler method in ES6

Explain handler method in ES6

A handler is an object whose properties are functions that define the behaviour of the proxy when an operation is performed on it. An empty handler will create a proxy that behaves, in almost all respects, exactly like the target. By defining any of a set group of functions on the handler object, you can customize specific aspects of the proxy’s behaviour. For example, by defining get() you can provide a customized version of the target’s property accessor.

Syntax:

new Proxy(target, handler)

proxy constructor(): Used to create a proxy object which takes two parameters.

Parameters: 

  • target: target object to wrap with Proxy. It can be any sort of object, including a native array, a function, or even another proxy.
  • handler: An object whose properties are functions that define the behaviour of the proxy when an operation is performed on it.

List of Handler Methods: This section lists all the handler methods you can define. Handler methods are sometimes called traps, because they trap calls to the underlying target object

Example: In this example, the target has two properties, string and num. We define a handler that returns a different value for num, and lets any other accesses through to the target.

Javascript




<script>
const target = {
    string: "GeeksForGeeks",
    num: 123
};
const handler = {
    get: function (target, prop, receiver) {
        if (prop === "string") {
            return "GeeksForGeeks";
        }
        return Reflect.get(...arguments);
    }
};
const obj = new Proxy(target, handler);
console.log(obj.string); // "GeeksForGeeks"
console.log(obj.num);    // "123"
</script>


Output:

GeeksForGeeks
123
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments