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.
Firstly, the difference between these two lines:
...and the difference between these two lines:
...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()
ornew Boolean()
. So for these,typeof
will return different values:However, for Object and Function, the difference between:
... is in syntax only.
Both
o1
ando2
have the sameprototype
, and the sameconstructor
, making them indistinguishable at runtime.