Search code examples
javascriptstring-literalsobject-literalfunction-literal

How to determine whether an object was created using an object literal or an Object constructor call?


More specifically, how would you determine if a certain object was created using a literal or not?

var s1 = new String();
var s2 = ""; // Literal

var o1 = new Object();
var o2 = {}; // Literal

var f1 = new Function();
var f2 = function(){}; // Literal

Obviously if you compare any two above, for example:

var o1 = new Object();
var o2 = {};

alert(o1 == o2);
alert(o1 === o2);

alert(typeof o1);
alert(typeof o2);

... The first two alerts will show false while the last two alerts will give [Object object]

Say for example, if I wanted to do this:

function isLiteral(obj, type) {
    // ...
}

... how would one go about doing this?

I have taken a look at How to determine if an object is an object literal in Javascript?, but it does not answer my question.


Solution

  • Firstly, the difference between these two lines:

    var s1 = new String();
    var s2 = ""; // Literal
    

    ...and the difference between these two lines:

    var o1 = new Object();
    var o2 = {}; // Literal
    

    ...are two different concepts.

    The first is the difference between a primitive value and an object, while the second is... different syntax for the same thing.


    Strings, numbers and booleans are primitive values, not objects, but can be wrapped as objects using new String(), new Number() or new Boolean(). So for these, typeof will return different values:

    var s1 = new String();
    typeof s1; // "object"
    var s2 = "";
    typeof s2; // "string"
    

    However, for Object and Function, the difference between:

    var o1 = new Object();
    var o2 = {};
    

    ... is in syntax only.

    Both o1 and o2 have the same prototype, and the same constructor, making them indistinguishable at runtime.