JavaScript Objects
Dateline: 10/05/99
Many programming languages are what we call "Object
Oriented." This means that you can create your own custom groupings
of functions and data in a way that makes sense to your programming approach.
To illustrate what I'm talking about, you could create define a type of
object (often called a "class") for an employee of a company.
This definition might include variables for salary, time with the company, job
title, social security number, etc. You may also want to define some
functions that apply to an employee; maybe a function to write a paycheck,
promote the employee, or whatever.
If you've used object oriented languages like C++ or Java, you're probably
following me here without difficulty. If not, read on: everything will
become clear.
JavaScript isn't exactly Object Oriented like C++ or Java. JavaScript
is referred to as "Object-Based." This means that you can't
define object types quite like you would in an object oriented language, but you
can still take advantage of most of the object functionality.
To define an object type in JavaScript, you must define it as a
function. You can use the "this" keyword to assign variables and
initial values (for the programming savvy, this is like using constructors in
object oriented languages).
function Employee()
{
this.Salary = 0;
this.TimeEmployed = 0;
this.JobTitle = "";
this.SocialSecurity = "";
}
To create this object (called an "instance" of the object), use the
"new" keyword.
var John = new Employee();
Now you can work with the values of each employee separately.
John.Salary = 100000;
John.TimeEmployed = 10;
John.JobTitle = "CEO";
John.SocialSecurity = "123-45-6789";
var Mary = new Employee();
Mary.Salary = 75000;
Mary.TimeEmployed = 5;
Mary.JobTitle = "JavaScript Programmer";
Mary.SocialSecurity = "987-65-4321"
To see a brief example of JavaScript objects in action, visit my Very
Simple Airline Reservation System.
Visit the message boards!
Previous Features
 |