La méthode hasOwnProperty () de l'objet JavaScript vérifie si l'objet a la propriété donnée comme sa propre propriété.
La syntaxe de la hasOwnProperty()
méthode est:
obj.hasOwnProperty(prop)
Voici obj
un objet.
Paramètres hasOwnProperty ()
La hasOwnProperty()
méthode prend en compte:
- prop - Le
String
nom ou le symbole de la propriété à tester.
Valeur renvoyée par hasOwnProperty ()
- Renvoie un
Boolean
indiquant si l'objet a ou non la propriété spécifiée comme sa propre propriété.
Remarques:
- Contrairement à l'
in
opérateur, cette méthode ne vérifie pas une propriété dans la chaîne de prototypes de l'objet. hasOwnProperty
renvoietrue
même si la valeur de la propriété estnull
ouundefined
.
Exemple: utilisation de hasOwnProperty ()
const obj = (); obj.property1 = 42; console.log(obj.hasOwnProperty("property1")); // true console.log(obj.hasOwnProperty("property2")); // false // Inherited properties return false console.log(obj.hasOwnProperty("toString")); // false
Production
vrai faux faux
Lecture recommandée: Javascript Object.propertyIsEnumerable ()