How to determine if an object is an object literal in Javascript?
What you want is:
Object.getPrototypeOf(obj) === Object.prototype
This checks that the object is a plain object created with either new Object()
or {...}
and not some subclass of Object
.
I just came across this question and thread during a sweet hackfest that involved a grail quest for evaluating whether an object was created with {} or new Object() (i still havent figured that out.)
Anyway, I was suprised to find the similarity between the isObjectLiteral() function posted here and my own isObjLiteral() function that I wrote for the Pollen.JS project. I believe this solution was posted prior to my Pollen.JS commit, so - hats off to you! The upside to mine is the length... less then half (when included your set up routine), but both produce the same results.
Take a look:
function isObjLiteral(_obj) { var _test = _obj; return ( typeof _obj !== 'object' || _obj === null ? false : ( (function () { while (!false) { if ( Object.getPrototypeOf( _test = Object.getPrototypeOf(_test) ) === null) { break; } } return Object.getPrototypeOf(_obj) === _test; })() ) ); }
Additionally, some test stuff:
var _cases= { _objLit : {}, _objNew : new Object(), _function : new Function(), _array : new Array(), _string : new String(), _image : new Image(), _bool: true }; console.dir(_cases); for ( var _test in _cases ) { console.group(_test); console.dir( { type: typeof _cases[_test], string: _cases[_test].toString(), result: isObjLiteral(_cases[_test]) }); console.groupEnd(); }
Or on jsbin.com...
http://jsbin.com/iwuwa
Be sure to open firebug when you get there - debugging to the document is for IE lovers.