 |
|
| |
 |
Creating Classy Menus with JavaScript
Use JavaScript classes and DHTML to build re-usable and easily modifiable client-side drop-down menus.
By Tom Duffy
|
|
bject Oriented Programming (OOP) has rapidly become the programming model of choice for any serious development work. There are a number of reasons why OOP has become so popularnot the least of which is code reuse. In this article I'll show you how to apply some OOP principles to JavaScript by revisiting the menu system built in my article Pop Goes the Menu.
OOP in JavaScript is a different animal than that found in more common OOP languages like Java and C++. In those languages, you abstract out real-world objects into their component parts and then assemble them in classes. The classes become the blueprints from which you create objects. Classes include everything an object needs to "know" about itself to be fully functional. So, all properties and methods associated with an object are included in the class. Then, when you are ready to create an object (in OOP: instantiate), you make a call to a constructora special method that creates an "instance" of the classan object.
JavaScript, however, doesn't support the traditional OOP concept of classes. It is more limited in that it only really supports functions and variables. You'll find that you'll have to bend some rules when writing JavaScript from an OOP perspective.
So what can you do to use OOP in JavaScript? Well, you can create functions that act like constructors and then make use of variables inside the constructors to create methods and properties. I'm often asked what the difference between a method and a function or between a property and a variable is. The simple answer is that when a function or variable is associated with an object, it is then a method or property. In other words, if you can tell an object to call some function on itself then it has called a method. Enough theory!
|
|
 |
TALK
BACK |
|
Do you use JavaScript classes? If not, why not? Do you think this article simplifies building cross-platform DHTML-based menus? Join the discussions a web.dhtml.general and web.dhtml.scripting to get answers, make comments, or help others with their problems.
|
|
|
|
|
|
|