The key difference between the two is in how they are intended to be used. A constructor, as its name suggests, is designed to create and set up multiple instances of an object. An object literal on the other hand is one-off, like string and number literals, and used more often as configuration objects or global singletons (e.g. for namespacing).
There are a few subtleties about the first example to note:
When the code is executed, an anonymous function is created and assigned to myObj
, but nothing else happens. methodOne
and methodTwo
don't exist until myObj
is explicitly called.
Depending on how myObj
is called, the methods methodOne
and methodTwo
will end up in different places:
myObj()
:
Since no context is supplied, the this
defaults to window
and the methods will become global.
var app1 = new myObj()
:
Due to the new
keyword, a new object is created and becomes the default context. this
refers to the new object, and the methods will get assigned to the new object, which subsequently gets assigned to app1
. However, myObj.methodOne
remains undefined.
myObj.call(yourApp)
:
This calls my myObj
but sets the context to be another object, yourApp
. The methods will get assigned to yourApp
, overriding any properties of yourApp
with the same names. This is a really flexible method that allows multiple inheritance or mixins in Javascript.
Constructors also allow another level of flexibility since functions provide closures, while object literals do not. If for example methodOne and methodTwo rely on a common variable password that is private to the object (cannot be accessed outside the constructor), this can be achieved very simply by doing:
var myObj = function(){
var variableOne = "ABCD1234";
this.methodOne = function(){
// Do something with variableOne
console.log(variableOne);
};
this.methodTwo = function(){
// Do something else with variableOne
};
};
myObj();
alert(variableOne); // undefined
alert(myObj.variableOne); // undefined
If you wanted to make variableOne
exposed (public) you'd do:
var myObj = function(){
this.variableOne = "ABCD1234";
this.methodOne = function(){
// Do something with variableOne
console.log(this.variableOne);
};
this.methodTwo = function(){
// Do something else with variableOne
};
};
myObj();
alert(variableOne); // undefined
alert(myObj.variableOne); // ABCD1234