Check if the object is

I need to check if a variable is a pure instance of an object. For example: HTMLElement is an instance of an object. But I really need to check if this is just an Object, for example {a: true, b: false}. It cannot check the array.

Note . I can use the newer Chrome features, if better.

+5
source share
2 answers

Check out 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
+8
source
var proto = Object.getPrototypeOf(obj);

var protoproto = Object.getPrototypeOf(proto);

if (proto === Object.prototype && protoproto === null) {
    //plain object
}

If you create objects with a prototype null, you can get rid of protoprotoand just compare protowith Object.prototypeor null.

, , Object.prototype, , Object.prototype.


:

var proto = Object.getPrototypeOf(obj);

if (proto && Object.getPrototypeOf(proto) === null) {
    // plain object
}

+2

All Articles