If you want to check if the object is a "simple" object, i.e. inherited directly from Object.prototype, then you should check this.
eg. the following first tests, if the value has an object somewhere on it with the prototype chain (and therefore will not generate an error for getPrototypeOf), and then checks whether its immediate [[prototype]] Object.prototype is:
function isPlainObject(value) { return value instanceof Object && Object.getPrototypeOf(value) == Object.prototype; }
Edit
If you want to check that the input is some kind of extended object, but not a function, etc., which is much less efficient, for example. test any list of objects you want to avoid:
function isJustObj(obj) { var notThese = [Function, Array, Date]; if (obj instanceof Object) { return !notThese.some(function(o) { return obj instanceof o; }); } return false; } function Foo(){} var tests = {'Array: ':[], 'Object: ' : {}, 'Foo instance:' : new Foo(), 'Function: ' : function(){}, 'Date: ' : new Date(), 'Host obj: ' : document.createElement('div') }; Object.keys(tests).forEach(function(test) { console.log(test + isJustObj(tests[test])); })
Note that this strategy determines if this value is some Object, and then checks to see if it is an instance of a specific set of constructors. This list of excluded things can become very large, since it is not possible to reasonably exclude host objects that, by their nature, can be indistinguishable from embedded objects based on some common test (see Is there an agrotic way to detect Javascript Host objects ?).
eg.
console.log instanceof Function // true console instanceof Object // true isPlainObject(console) // false
So, you either check to see if Object.prototype is direct [[prototype]] , or create a long list of constructors for testing. This list will expire very quickly, given the variety of host environments available and the freedom for developers to expand it. In addition, before trying to use it, you need to test each member of the host object, since it may not exist for the specific host on which the code is running.
source share