Does the hasOwnProperty method always make sense in JavaScript?
Here we can see what types of objects in JavaScript / ECMAScript are evaluated before false
.
My question is, if a variable is evaluated as true
, is its method guaranteed hasOwnProperty
?
In other words, is the following test safe?
if (bar && bar.hasOwnProperty("foo")) { ... }
My goal is to prevent exceptions like Cannot read property 'hasOwnProperty' of null
.
My Application Scenario: In AngularJS Service Error Handler $http
I want to be prepared for all situations. This is a bit tricky for me because I am not very good at JavaScript and the various situations in which this error handler might be called cannot be easily tested. The error handler function has the following signature:
function(data, status, headers, config) {}
In the body of the function, I evaluate data
like this:
if (data && data.hasOwnProperty("error")) {
alert(data.error);
}
Is it safe for you under all circumstances? Safe in the sense that this test does not throw an exception, no matter how AngularJS actually calls the error handler.
Not.
Here's one:
var bar = Object.create(null);
Here's another one with hasOwnProperty
, but not much better:
var bar = {hasOwnProperty:function(){ throw "bouh" }};
But you can call
Object.prototype.hasOwnProperty.call(bar, "foo")
Note that you can avoid evaluating the truth by doing
if (Object.prototype.hasOwnProperty.call(Object(bar), "foo")) {