Java Reference
In-Depth Information
Creating Objects
To create an object literal, simply enter a pair of curly braces. The following example creates
an empty object that is assigned to the variable spiderman :
var spiderman = {};
It's also possible to create an object using a constructor function. This example will create
an empty object:
var spiderman = new Object();
This method is not recommended, however, and the object literal notation is the preferred
way of creating objects. The obvious reason is because it requires less typing; a constructor
takes more steps in the background, which can cause programs to run slower.
Accessing Properties
You can access the properties of an object using the dot notation that we've already seen in
previous chapters:
<< "Superman"
You can also access an object's properties using bracket notation ―the property is repres-
ented by a string inside square brackets, so needs to be placed inside single or double quota-
tion marks:
<< "Superman"
Dot notation is much more common, but bracket notation has a few advantages: It is the
only way to access nonstandard property and method names that don't follow the variable
naming rules. It also lets you evaluate an expression and use it as the object key:
Search WWH ::

Custom Search