Search code examples
javascriptoopobject-literal

How to determine if an object is an object literal in Javascript?


Is there any way to determine in Javascript if an object was created using object-literal notation or using a constructor method?

It seems to me that you just access it's parent object, but if the object you are passing in doesn't have a reference to it's parent, I don't think you can tell this, can you?


Solution

  • 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.