If I do this:
for (var i in obj) {
if (obj.hasOwnProperty(i)) console.log("Has property: " + i);
else console.log("Doesn't have property: " + i);
}
Will obj.hasOwnProperty(i)
ever return false
? If so, when?
The idea of using hasOwnProperty within a loop is to resolve to false when looping over inherited properties. This avoids what Douglas Crockford refers to as a "deep-dredge."
Example from https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/hasOwnProperty :
var buz = {
fog: 'stack'
};
for (var name in buz) {
if (buz.hasOwnProperty(name)) {
alert("this is fog (" + name + ") for sure. Value: " + buz[name]);
}
else {
alert(name); // toString or something else
}
}
Example from https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/hasOwnProperty - doesn't show when hasOwnProperty
can return false.
Here's a test case that does show that:
// From some library or earlier in your code
Object.prototype.xxx = "xxx";
// Your object
var data = { member: "member" };
for (var key in data) {
if( data.hasOwnProperty(key) ) {
alert(key); // alert("member")
}
else {
alert(key); // alert("xxx")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With