I need to check if a variable is a pure Object instance. For example: a HTMLElement is instanceof Object. But I really need to check if it is only an Object, like {a: true, b: false}
is. It not can validate an Array.
Note: I can use newer features of Chrome, if better.
Check the constructor. Seems to work in all browsers
if (a.constructor === Object)
// Good for arrays
([]).constructor === Object => false
// Good for HTMLElements
document.body.constructor === Object => false
var proto = Object.getPrototypeOf(obj);
var protoproto = Object.getPrototypeOf(proto);
if (proto === Object.prototype && protoproto === null) {
//plain object
}
If you'll be creating objects with a null
prototype, you could get rid of the protoproto
, and just compare proto
to Object.prototype
or null
.
The danger of that is that it doesn't guard against being passed Object.prototype
itself, perhaps causing accidental extensions of Object.prototype
.
A little shorter and safer like this:
var proto = Object.getPrototypeOf(obj);
if (proto && Object.getPrototypeOf(proto) === null) {
// plain object
}
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