I just happened to notice that when assigning a variable as an Object
, the typeof the variable is a 'function' whereas if I assign it as an empty object using object literal notation {}
or instantiate as a new Object
, the typeof variable is an object.
What's the difference here?
Please note, I'm not asking the difference between Object literal notation and constructor notation.
Objects created using object literal are singletons, this means when a change is made to the object, it affects the object entire the script. Whereas if an object is created using constructor function and a change is made to it, that change won't affect the object throughout the script.
The main difference here is what you can do with it. With the constructor function notation you create an object that can be instantiated into multiple instances (with the new keyword), while the literal notation delivers a single object, like a singleton.
In plain English, an object literal is a comma-separated list of name-value pairs inside of curly braces. Those values can be properties and functions. Here's a snippet of an object literal with one property and one function. var greeting = {
Now the question is when should we be using Literal notation and constructor notation. The point is when we need only one instance with the same values then we can go with the literal notation else if we may need multiple instances, like the instance of a class, we can go for the constructor notation.
The global symbol Object
refers to the Object constructor function. Assigning Object
to a variable just makes a copy of that reference, and is completely different from assigning a reference to a new empty object ({}
).
Perhaps you're thinking of:
var a = new Object();
var b = {};
Those two statements do the same thing.
When you assign a variable as an Object it references the Object function onto it whereas when you do new Object or {} it just creates a plain object with the constructor method of it's parent Object
You can understand more with screenshots
a = Object;
doesn't create a new object. It assigns the constructor function to your variable a
. To create a new object, use this code: a = new Object();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With