How to check if the object isEmpty () if Object.prototype has been modified?

I want to check if the object is empty: {} . Commonly used are the following:

 function isEmpty(obj) { for (var prop in obj) { if (obj.hasOwnProperty(prop)) return false; } return true; } 

But suppose the Object prototype was added 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 destroy the prototype of the object, change its constructor and all kinds of hacks. Nothing worked, but maybe I did it wrong (probably).

+6
source share
1 answer

Just remove the obj.hasOwnProperty filter:

 function isEmpty(obj) { for (var prop in obj) { return false; } return true; } 

Demo

That way, it will also tell you if there are any properties or something in the prototype chain, if you need it.

Alternatively you can change

 if (obj.hasOwnProperty(prop)) 

to

 if (!obj.hasOwnProperty(prop)) 

if you only want to know something is messing with a prototype with him.

+3
source

Source: https://habr.com/ru/post/904960/


All Articles