• JavaScript Video Tutorials

JavaScript Handler get() Method



The handler.get() method in JavaScript is part of the Proxy object, enabling interception of property access on target objects. It takes two arguments: the target object and the accessed property. When the property gets accessed, this method is triggered, allowing custom behavior such as logging, validation before returning the property value. It is commonly used for implementing features like data validation or debugging in JavaScript applications. The handler.get() provides a powerful way to customize how properties are accessed in JavaScript objects, enabling developers to create more flexible code.

Syntax

Following is the syntax of JavaScript handler.get() method −

new Proxy(target, {
   get(target, property, receiver) {}
});

Parameters

  • target − It holds the target object.
  • property − It is the name or symbol of the property which is to be get.
  • receiver − The proxy or the object that inherits from proxy.

Return value

This method returns any value.

Example 1

Let's look at the following example, where we are going to access the property of a object.

<html>
<style>
body {
   font-family: verdana;
   color: #DE3163;
}
</style>
<body>
<script>
const x = {
   car: 'RS6',
   model: 2018
};
const y = {
   get: function(target, prop) {
      return x[prop];
   }
};
const z = new Proxy(x, y);
document.write(z.car);
</script>
</body>
</html>

Output

If we execute the above program, it will displays a text on the webpage.

Example 2

Consider another scenario where we are going to access the property using array indexing.

<html>
<style>
body {
   font-family: verdana;
   color: #DE3163;
}
</style>
<body>
<script>
const x = [11, 23, 33, 44];
const y = {
   get: function(target, prop, receiver) {
      if (prop === 'first') {
         return x[0];
      }
      return x[prop];
   }
};
const z = new Proxy(x, y);
document.write(z[1]);
</script>
</body>
</html>

Output

On executing the above script, it will displays a number on the webpage.

Example 3

In the following example, we are going to check whether the property exists on the object or not.

<html>
<style>
body {
   font-family: verdana;
   color: #DE3163;
}
</style>
<body>
<script>
const x = {
   bike: "Hayabusa",
   model: 2024
};
const y = {
   get: function(target, prop, receiver) {
      if (prop in x) {
         return x[prop];
      } else {
         return 'Property does not exist.';
      }
   }
};
const proxy = new Proxy(x, y);
document.write(proxy.bike + " < br > ");
document.write(proxy.engine);
</script>
</body>
</html>

When we execute the above code, it will generate an output consisting of the text displayed on the webpage.

Advertisements