I want to test whether an object is empty: {}
. The following is typically used:
function isEmpty(obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop))
return false;
}
return true;
}
But suppose the Object
prototype was added to as follows:
Object.prototype.Foo = "bar";
Tests:
alert(isEmpty({})); // true
Object.prototype.Foo = "bar";
alert({}.Foo); // "bar" oh no...
alert(isEmpty({})); // true ...**huh?!**
I tried to nuke the object's prototype, change it's constructor, and all manner of such hacks. Nothing worked, but maybe I did it wrong (probable).
Just remove the obj.hasOwnProperty
filter:
function isEmpty(obj) {
for (var prop in obj) {
return false;
}
return true;
}
This way it will also tell you if contains any properties or if anything is in the prototype chain, if that's what you want.
Alternatively you can change
if (obj.hasOwnProperty(prop))
to
if (!obj.hasOwnProperty(prop))
if you only want to know if something is messing with it's prototype.
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