1var person = {
2 "first_name": "Bob",
3 "last_name": "Dylan"
4};
5person.hasOwnProperty('first_name'); //returns true
6person.hasOwnProperty('age'); //returns false
1if (someVar.hasOwnProperty('someProperty') ) {
2 // do something();
3} else {
4 // do somethingElse();
5}
1var person = {'first_name': 'bill','age':20};
2
3if ( person.hasOwnProperty('first_name') ) {
4 //person has a first_name property
5}
6
1// JavaScript does not protect hasOwnProperty method
2var foo = {
3 // overriding foo's default hasOwnProperty method
4 hasOwnProperty: function() {
5 return false;
6 },
7 bar: 'data'
8};
9foo.hasOwnProperty('bar'); // false always
10
11// Hence, to prevent this, use Object.prototype.hasOwnProperty as follows-
12Object.prototype.hasOwnProperty.call(foo, 'bar'); // true
1The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).
2
3const object1 = {};
4object1.property1 = 42;
5
6console.log(object1.hasOwnProperty('property1'));
7// expected output: true
8
9console.log(object1.hasOwnProperty('toString'));
10// expected output: false
11
1//hasOwnPropertydevuelve un valor booleano que indica si el objeto al que está llamando tiene una propiedad con el nombre del argumento. Por ejemplo:
2
3var x = {
4y: 10};
5console.log(x.hasOwnProperty("y")); //true
6console.log(x.hasOwnProperty("z")); //false