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.
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.
They both do the same thing (unless someone's done something unusual), other than that your second one creates an object and adds a property to it. But literal notation takes less space in the source code. It's clearly recognizable as to what is happening, so using new Object(), you are really just typing more and (in theory, if not optimized out by the JavaScript engine) doing an unnecessary function call.
These
person = new Object() /*You should put a semicolon here too.
It's not required, but it is good practice.*/
-or-
person = {
property1 : "Hello"
};
technically do not do the same thing. The first just creates an object. The second creates one and assigns a property. For the first one to be the same you then need a second step to create and assign the property.
The "something unusual" that someone could do would be to shadow or assign to the default Object global:
// Don't do this
Object = 23;
In that highly-unusual case, new Object will fail but {} will work.
In practice, there's never a reason to use new Object rather than {} (unless you've done that very unusual thing).
What's the difference between an object literal and JSON? When do you use which?
Object and Object Literals in javascript - Stack Overflow
javascript - Should I be using object literals or constructor functions? - Stack Overflow
What are the pros and cons of using object literal notation vs class notation?
Videos
If you don't have behaviour associated with an object (i.e. if the object is just a container for data/state), I would use an object literal.
var data = {
foo: 42,
bar: 43
};
Apply the KISS principle. If you don't need anything beyond a simple container of data, go with a simple literal.
If you want to add behaviour to your object, you can go with a constructor and add methods to the object during construction or give your class a prototype.
function MyData(foo, bar) {
this.foo = foo;
this.bar = bar;
this.verify = function () {
return this.foo === this.bar;
};
}
// or:
MyData.prototype.verify = function () {
return this.foo === this.bar;
};
A class like this also acts like a schema for your data object: You now have some sort of contract (through the constructor) what properties the object initializes/contains. A free literal is just an amorphous blob of data.
You might as well have an external verify function that acts on a plain old data object:
var data = {
foo: 42,
bar: 43
};
function verify(data) {
return data.foo === data.bar;
}
However, this is not favorable with regards to encapsulation: Ideally, all the data + behaviour associated with an entity should live together.
It essentially boils down to if you need multiple instances of your object or not; object defined with a constructor lets you have multiple instances of that object. Object literals are basically singletons with variables/methods that are all public.
// define the objects:
var objLit = {
x: 0,
y: 0,
z: 0,
add: function () {
return this.x + this.y + this.z;
}
};
var ObjCon = function(_x, _y, _z) {
var x = _x; // private
var y = _y; // private
this.z = _z; // public
this.add = function () {
return x + y + this.z; // note x, y doesn't need this.
};
};
// use the objects:
objLit.x = 3;
objLit.y = 2;
objLit.z = 1;
console.log(objLit.add());
var objConIntance = new ObjCon(5,4,3); // instantiate an objCon
console.log(objConIntance.add());
console.log((new ObjCon(7,8,9)).add()); // another instance of objCon
console.log(objConIntance.add()); // same result, not affected by previous line
What I mean by object notation is defining a class as an object, like this:
var food = {
var taste : "";
create: function(initTaste){
var temp = Object.create(this);
this.taste = initTaste;
return temp;
}var sandwich = food.create("salty"); var candy = food.create("sweet");
While class notation is typical "class food" format.
Which one would be advisable to use and why? Also, if I were to convert the above example into "class" what would it look like?
Mozilla.org has very good explanation of the different literals with examples.
Array Literals
An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets ([]). When you create an array using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified.
Object Literals
An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). You should not use an object literal at the beginning of a statement. This will lead to an error or not behave as you expect, because the { will be interpreted as the beginning of a block.
The difference is the way they're indexed.
Objects have name, value pairs which are not ordered. In some browsers the order you added values will be the order you get when you traverse the object but not in all. The name is usually a string.
Arrays are numerically indexed and the order is totally reliable
Yes, that's exactly what object literal means. A definition of a javascript object which may contain comma separated definition of properties, functions, ...
Object literals are formed using the following syntax rules:
- A colon separates property name from value.
- A comma separates each name/value pair from the next.
- There should be no comma after the last name/value pair. Firefox won't object if you add it, but Internet Explorer will trigger an error: 'Expected identifier, string or number'.
An object literal is a way to declare an object.
You would write
var myObject = {}; // with or without members
instead of
var myOject = new Object();
You can also use array literals:
var myArray = [];
instead of
var myArray = new Array(); // with or without members
It's shorter, of course but it also bypasses the constructor so it's supposed to be more efficient.
In JavaScript, the keys in object literal notation are treated as strings whether or not they are in quotes. Thus, with this:
var car = { manyCars : {a: "Saab", "b": "Jeep"}, 7: "Mazda" };
If you then do this:
for (var k in car) { console.log("key: " + k + " (type: " + typeof(k) + ")"); }
the output will be:
key: 7 (type: string)
key: manyCars (type: string)
Note that the (apparently) numeric key 7 is also a string. You can even use JavaScript keywords as keys in an object literal.
Note that when accessing a value by key, the rules are more stringent. For instance, you must use subscript notation and quotes when a key is a reserved word. Also, a bare key in an object literal must (if it isn't a numeric literal) be a valid JavaScript identifier name, so it cannot contain spaces, commas, or JavaScript operators (+, =, etc.).
In JavaScript objects literals are made up of key-value pairs. Keys in JavaScript are always strings while values may be of any data type.
JavaScript provides syntactic sugar for defining keys. For example unlike string literals you don't need to quote keys. Hence the following two examples are equivalent:
{ x: 0 } // example 1
{ "x": 0 } // example 2
However this syntactic sugar only works for identifiers that don't have any whitespace (i.e. spaces, tabs, newlines, etc.) in between them. For example, the following is invalid in JavaScript:
{ a property: 0 } // whitespace not allowed in identifiers
However you can workaround this limitations by quoting the identifier:
{ "a property": 0 } // valid
You may also use boolean (true or false), number literals and undefined and null as keys. However remember that they are coerced to strings. Hence you can do:
var o = {
undefined: 1,
null: 2,
true: 3,
false: 4,
0: 5
};
Then you can access them as:
alert(o.undefined); // 1
alert(o.null); // 2
alert(o.true); // 3
alert(o.false); // 4
alert(o[0]); // 5
The last statement is important. Number literals by themselves do not classify as valid identifiers. Hence you need to use the array bracket notation ([]) instead of the dot notation (.) to access it.
Since all keys in JavaScript are strings you could even do:
alert(o["undefined"]); // 1
alert(o["null"]); // 2
alert(o["true"]); // 3
alert(o["false"]); // 4
alert(o["0"]); // 5
However you can't use objects, arrays or functions as keys. For example the following is invalid:
{ {1: 2}: 3 } // objects can't be used as keys
{ [1]: 2 } // arrays can't be used as keys
{ function () {}: true } // functions can't be used as keys
That's all you need to know about object literals.