• JavaScript Video Tutorials

JavaScript Handler has() Method



The handler.has() method is a part of the proxy object that allows you to define a custom behavior for fundamental operations on an object. Specially, the handler.has() is invoked when the in operator was used to check if a property exists on the object. It accepts two arguments: the target object and the property key being checked.

The handler.has() method returns a Boolean value indicating whether the property is present on the object. The handler return true if the property is found indicating that the property exists. If not, it returns false.

Syntax

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

new Proxy(target, {
   has(target, prop) {}
});

Parameters

  • target − It holds the target object.
  • property − It is the name or symbol of the property to check for existence.
  • receiver − It is the name or symbol of the property which is to be get.

Return value

This method returns a Boolean value.

Example 1

Let's look at the following example, where we are going to check whether a property exists in an object or not.

<html>
<style>
body {
   font-family: verdana;
   color: #DE3163;
}
</style>
<body>
<script>
let x = {
   car: 'POLO GT',
   model: 2024
};
let y = {
   has(a, b) {
      return b in a;
   }
};
let c = new Proxy(x, y);
document.write('car' in c);
</script>
</body>
</html>

Output

If we execute the above program, it will displays a text on the webpage indicating that the property exists.

Example 2

Consider another scenario where we are going to prevent access to certain properties which is effectively hidden from the proxy.

<html>
<style>
body {
   font-family: verdana;
   color: #DE3163;
}
</style>
<body>
<script>
let x = {
   bike: 'Hayabusa',
   model: 2025
};
let y = {
   has(a, b) {
      return b !== 'bike';
   }
};
let c = new Proxy(x, y);
document.write('bike' in c);
</script>
</body>
</html>

Output

On executing the above script, it will displays false on the webpage indicating that the property was hidden.

Example 3

In the following example, we are going to check whether the value of the property is 'POLO GT' or not and retrieve the output.

<html>
<style>
body {
   font-family: verdana;
   color: #DE3163;
}
</style>
<body>
<script>
let x = {
   car: 'POLO GT',
   age: 25
};
let y = {
   has(a, b) {
      return a[b] === 'POLO GT';
   }
};
let c = new Proxy(x, y);
document.write('car' in c);
</script>
</body>
</html>

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

Advertisements