JavaScript | handler.has() Method

The handler.has() method in JavaScript is used to “hide” any property that you want. It is a trap for an operator. It returns the Boolean value.

Syntax:

const p = new Proxy(target, {
  has: function(target, prop) {
  }
});

Parameters: This method accept two parameters as mentioned above and described below:

  • target: This parameter is the target object.
  • prop: This parameter is the property which is going to be check for existence.

Return value: This method return a Boolean value true if you want the property to be accessed.

Below examples illustrate the handler.has() method in JavaScript:



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
const handler1 = {
  has (target, key) {
    if (key[1] === '1') {
      return false;
    }
    return key in target;
  }
};
  
const monster1 = {
  p1roperty1: 'GeeksforGeeks',
  property2: 4
};
  
const proxy1 = new Proxy(monster1, handler1);
console.log('property2' in proxy1);
console.log('p1roperty1' in proxy1);
console.log('p1roperty1' in monster1);
</script>

chevron_right


Output:

true
false
true

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
var s={  
  value:1  
}  
var p = new Proxy(s, {  
  has: function(target, prop) {  
    console.log( prop);  
    return false;  
  }  
});  
console.log('prop' in p); 
  
var p1 = new Proxy(s, {  
  has: function(target, prop) {  
    console.log( prop);  
    return true;  
  }  
});  
console.log('prop' in p1);
</script>

chevron_right


Output:

"prop"
false
"prop"
true

Supported Browsers: The browsers supported by handler.has() method are listed below:

  • Google Chrome
  • Firefox
  • Opera
  • Safari
  • Edge

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.