I have a custom Javascript object that I create with new
, and assign attributes to based on creation arguments:
function MyObject(argument) {
if (argument) {
this.prop = "foo";
}
}
var objWithProp = new MyObject(true); // objWithProp.prop exists
var objWithoutProp = new MyObject(false); // objWithoutProp.prop does not exist
What's the correct way to test for the existence of the prop
property of the objects? I've seen the following ways used, but I'm not sure if any of these ways is the best way:
if (obj.prop) {}
if (obj.hasOwnProperty("prop")) {}
if ("prop" in obj) {}
Specifically, I'm only interested in testing if the property is explicitly defined for this object, not in the prototype chain. In addition, the value will never be set to null
or undefined
, but it could be something like an empty object or array. However, if you want to include what the correct way is if those could be the case, feel free.