Reputation: 27212
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.
Upvotes: 3
Views: 295
Reputation: 350335
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')
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. ;-)
Upvotes: 4