JavaScript Objects
Objects
We've already seen how JavaScript uses already defined objects. It turns out you can create your own Objects as well. Just like in Java, JavaScript objects have methods and properties, but since it is in JavaScript, you don't have typed attributes. In addition, JavaScript doesn't have all of the accessory modifiers, so you don't necessarily write getter and setter methods. Instead you access the attributes directly.
foo.name = "Fred";
You've seen this with the DOM object model already.
Defining an object
Again, JavaScript varies from Java objects greatly. There are no formal class definitions required, instead you can make an object and you define attributes by assigning values to the attributes.
For example, let's make an address Object:
address = new Object();
address.street="11100 Johns Hopkins Road";
address.city="Laurel";
address.state="MD";
address.zip="20723"
Adding methods to an object involves creating an attribute that matches the method name, and then assigning the method name to that attribute (sounds circular, doesn't it?). You can then define the function separately.
address.validZip = validZip;
// is the zip code within an expected range (I know, this really doesn't validate it
// but you get the picture...
function validZip() {
return this.zip > 0 && this.zip < 10000;
}
Note the use of the "this" reference, similar to Java. It qualifies the variable to be that defined in the class, not the argument variable.
You can make a function (works like a class template), that defines the structure of an object, and even adds methods. This allows you to create Objects later on without going through the steps above each time
function dimension(width, height) {
this.height = height;
this.width = width;
this.getArea = getArea;
this.setWidth = setWidth;
this.setHeight = setHeight;
}
function getArea() {
return width * height;
}
function setWidth(width) {
this.width = width;
}
function setHeight(height) {
this.height = height;
}
Advanced Structure
The above examples are very simple. The methods defined aren't the most effective use of memory, since a separate copy of the method code will be created for each object that you derive from the class. You can define "prototype" methods, that mean that all objects will share the same copy of the code. When using the prototype methods, you can even define the methods inside of the Object definition. Let's look at our "dimension" prototype again.
function dimension(width, height) { this.height = height; this.width = width; this.getArea = getArea; this.setWidth = setWidth; this.setHeight = setHeight; this.prototype.getArea = function() { return width * height; } this.prototype.setWidth = function (width) { this.width = width; } this.prototype.setHeight = function(height) { this.height = height; }
This looks a lot more like Java coding standards and is easier to read.