Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Handler has() Method

JavaScript Handler has() Method

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: 'neveropen',
    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.

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!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments