This section provides a quick description of object literals or initializers for creating new objects of the 'Object' type. A tutorial example is provided on how to initialize an object with two properties and two methods.
In previous sections we learned that objects of "Object" type can be created with the constructor function
"new Object()".
JavaScript also support a simpler way to create objects of "Object" type using object literals in the format of:
{property1: value1, property2: value2, ...}
where "property1" and "property2" are property or method names. In JavaScript language, properties and methods
in an object are really managed in an identical way.
An object literal is also called object initializer, because it allows you to create a new object and
to initialize it with properties and methods in a single operation.
Using an object literal to create an object has the same result as using the constructor.
But object literals are much easier to use. The following two code segments are identical.
But the first one is much simpler:
// Creating an object with an object literal
var obj = {property1: value1, property2: value2, ...};
// Creating an object with the constructor
var obj = new Object();
obj.property1 = value1;
obj.property2 = value2;
...;
Here is a tutorial example of creating an object of the "Object" type with an object literal, or initializer:
<html>
<!-- Object_Literal.html
Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<head>
<title>Object Literals of "Object" Type</title>
</head>
<body>
<pre>
<script type="text/javascript">
// Using "this" to get the properties
function myToString() {
return '"'+this.title + '" by '+this.author;
}
// Using "this" to get the "toString" method
function showAll() {
window.alert(this.toString());
}
// Using object literal format
var myBook = {
author: "Herong Yang",
title: "JavaScript Tutorials",
print: showAll,
toString: myToString
};
// Calling the method on "myBook"
myBook.print();
</script>
</pre>
</body>
</html>
If you run this tutorial example, you will get the same result as the example in the previous section: "JavaScript Tutorials" by Herong Yang.