简体   繁体   中英

Inconsistent behaviour of object method 'hasOwnProperty'

Problem Statement :

If object having same property name as JavaScript predefined method have. It fails to execute and gives below error.

Uncaught TypeError: obj.hasOwnProperty is not a function

Code :

 var obj1 = { "key1":"value1", "key2":"value2" } console.log(obj1.hasOwnProperty('key2')); // true var obj2 = { "key1":"value1", "key2":"value2", "hasOwnProperty": "value3" } console.log(obj2.hasOwnProperty('key2')); // Uncaught TypeError: obj.hasOwnProperty is not a function 

Code Explanation :

In above code snippet i am trying to check if the key of an object exist or not.

Hence, In first console statement it returns true as obj1 having property named as key2 but it fails when new property with named as "hasOwnProperty": "value3" added in to the object.

As we know using of the JavaScript object method name as an object property is not a good practice but API team do not know about the JavaScript predefined methods. Hence, they can send it in the API response.

Expectation :

I want to check using hasOwnProperty() method that key2 exist in obj2 or not which having hasOwnProperty property in it.

Any help will be highly appreciable. Thanks

You can get around that by using the prototype method and call to pass your object as first argument:

 var obj2 = { "key1":"value1", "key2":"value2", "hasOwnProperty": "value3" } console.log(Object.prototype.hasOwnProperty.call(obj2, 'key2')); 

A bit shorter is using {} instead of Object.prototype , but that incurs some miniscule overhead:

{}.hasOwnProperty.call(obj2, 'key2')

Remark

The object you use to get access to the hasOwnProperty property really is irrelevant, as long as it inherits from Object.prototype . So you can make things look complicated by using some other unrelated (or seemingly related) object:

Math.hasOwnProperty.call(obj2, 'key2')

Function.hasOwnProperty.call(obj2, 'key2')

obj1.hasOwnProperty.call(obj2, 'key2')

"".hasOwnProperty.call(obj2, 'key2')

NaN.hasOwnProperty.call(obj2, 'key2')

JSON.hasOwnProperty.call(obj2, 'key2')

Object.hasOwnProperty.call(obj2, 'key2')

... etc. ;-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM