Javascript: Object Orientation
An OO approach is a key part of your Javascript/Ajax programming arsenal. There are multiple ways to program Javascript in an object-oriented way. The Prototype library adds some helper constructs to facilitate object orientation, as do many other Javascript libraries. Regardless of which framework you use (or if you choose to use none at all), an object-oriented approach can make your Ajax programming easier.
Here, I'm demonstrating a basic syntax for OO; you can use this syntax literally, or use it to enhance your understanding of the various framework-based OO approaches available out here.
Defining the Class
In Javascript, classes are defined as functions. The "new" keyword together with the function gives you new instances of the class. Here's an example:
// a Person class
function Person (sName, nAge) {
this.sName = sName;
this.nAge = nAge;
}
// add a method to the class by adding a function to its prototype
Person.prototype.tellMe = function() {
return ("My Name is "+this.sName+". I am "+this.nAge+" years old");
}
That's all there is too it. You have now defined a class (Person), with one method (tellMe).
Using the Object
To use the Person class we just defined:
var oPerson = new Person("Bob", 28);
alert (oPerson.tellMe());
. . . will give us:
Where's the Constructor?
In this example, all the code inside function Person() is the constructor -- this code gets executed each time you use the function to create a new instance of the class, and sets the members of the instance (sName and nAge) to the values passed to the function.There's lots more to OO Javascript programming
You can model inheritance and more with Javascript. A good place to learn more is webreference's Object-Oriented Programming with JavaScript series.
