ptg16476052
490 LESSON 17: Introducing JavaScript
Object properties are accessed through what’s known as dot notation. You can also
access properties as though they are array indexes. For example, if you have an object
named car with a property named color, you can access that property in two ways:
car.color = "blue";
car["color"] = "red";
You can also add your own properties to an object. To add a new property to the car
object, I just have to declare it:
car.numberOfDoors = 4;
There are a number of ways to create objects, but you should stick to the best one. To
create an object, you can use an object literal, which is similar to the array literal I just
described:
var car = { color: "blue", numberOfDoors: 4, interior: "leather" };
That defines an object that has three properties. As long as the properties of the object
follow the rules for variable names, there’s no need to put them in quotation marks. The
values require quotation marks if their data type dictates that they do. You can name
properties whatever you like, though, as long as you use quotation marks.
In addition to properties, objects can have methods. Methods are just functions associated
with the object in question. This may seem a bit odd, but methods are properties of an
object that contain a function (as opposed to a string or a number). Here’s an example:
car.description = function() {
return color + ' car ' + ' with '
+ numberOfDoors + ' and a ' + interior + ' interior';
}
As you can see, this is a bit different from the function declarations you’ve seen before.
When you declare a method, instead of specifying the function name in the function
statement, you assign an anonymous function to a property on your object. You can spec-
ify parameters for your methods just as you specify them for functions.
After you’ve added a method to an object, you can call it in the same way the methods of
built-in objects are called. Here’s how it works:
document.write(car.description());
The core JavaScript language contains lot of built-in objects—too
many to cover here. For more information about these objects,
look at the JavaScript documentation provided by Mozilla or
Microsoft.
NOTE