What is the difference between this constructor-based syntax for creating an object:
person = new Object()
...and this literal syntax:
person = {
property1 : "Hello"
};
It appears that both do the same thing, although JSLint prefers you use object literal notation.
Which one is better and why?
There is no difference for a simple object without methods as in your example. However, there is a big difference when you start adding methods to your object.
Literal way:
function Obj( prop ) {
return {
p : prop,
sayHello : function(){ alert(this.p); },
};
}
Prototype way:
function Obj( prop ) {
this.p = prop;
}
Obj.prototype.sayHello = function(){alert(this.p);};
Both ways allow creation of instances of Obj
like this:
var foo = new Obj( "hello" );
However, with the literal way, you carry a copy of the sayHello
method within each instance of your objects. Whereas, with the prototype way, the method is defined in the object prototype and shared between all object instances.
If you have a lot of objects or a lot of methods, the literal way can lead to quite big memory waste.