JavaScript handler.has() method in JavaScript is used to “hide” any property that you want. It is a trap for in operator. It returns the Boolean value. If you want to access the property, it returns the Boolean value true; otherwise, it returns false. Whether the key was included with the original object or not.
Syntax:
const p = new Proxy(target, {
has: function(target, prop) {
}
});
Parameters: This method accepts two parameters as mentioned above and described below:
- target: This parameter is the target object.
- prop: This parameter is the property that is going to be checked for existence.
Return value: This method returns a Boolean value true if you want the property to be accessed.
Below examples illustrate the handler.has() method in JavaScript:
Example 1: In this example, we will check if the object has the values or not using the handler.has() method in JavaScript.
javascript
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);
|
Output:
true
false
true
Example 2: In this example, we will check if the object has the values or not using the handler.has() method in JavaScript.
javascript
let s = {
value: 1
}
let p = new Proxy(s, {
has: function (target, prop) {
console.log(prop);
return false ;
}
});
console.log( 'prop' in p);
let p1 = new Proxy(s, {
has: function (target, prop) {
console.log(prop);
return true ;
}
});
console.log( 'prop' in p1);
|
Output:
"prop"
false
"prop"
true
Supported Browsers: The browsers supported by handler.has() method are listed below:
- Google Chrome 49 and above
- Edge 12 and above
- Firefox 18 and above
- Opera 36 and above
- Safari 10 and above
We have a complete list of Javascript Proxy/handler methods, to check those go through the Javascript Proxy/handler Reference article.