Question:
I'm just beginning to learn JavaScript and I would like to know the meanings of a few terms.
- What is a variable?
- What is a function?
- What is an object?
- What is a property?
- What is a method?
These are good questions for a beginner to ask. You can't understand JavaScript without knowing the answers to these questions, so let's tackle them one at a time.
Variables in JavaScript are similar to the variables you may have studied in high school algebra. You can think of variables as "holding places" where values are stored and retrieved. Each holding place has a unique name, which is any combination of letters and numbers that does not begin with a number. (In JavaScript, the characters a-z, A-Z, and the underscore character "_" are all considered to be unique letters.)
Unlike other programming languages, where variables can only hold certain types of data, JavaScript variables are typeless. This means that any variable can take on any type of data -- numbers, strings, arrays, objects, etc. Because JavaScript variables are not restricted to specific types of values, there is no need to "declare" them before using them. Instead, memory is automatically allocated to store the variable when the variable is assigned its first value.
The following JavaScript statement creates a variable named greeting
and uses it to store the value "hello":
greeting = "Hello";
The variable greeting
can now be used in expressions that produce additional values. For example, the following JavaScript statement shows how to modify greeting
's value so that it contains an even friendlier greeting:
greeting = greeting + ", my friend.";
When this statement is executed, the value of greeting
changes from "Hello" to "Hello, my friend."
A JavaScript function is a "recipe" of instructions (i.e., statements or commands) whose purpose is to accomplish a well-defined task. When the JavaScript interpreter (i.e., your browser) executes a function, it processes these instructions, one by one, until there are no more instructions in the function to execute.*
Some functions can be thought of as "processing units" that accept data from one end and produce results at the other. A function's input is called its parameters; its output is called the return value.
For example, a JavaScript function whose purpose is to compute the square of a number might be defined as follows:
function square (number) { var result = number * number; return result; }
In this "square
" function, the parenthesized variable "number
" is called a parameter. It represents the input, or the value to be squared. The output of square
is the value of the expression following the return
statement -- in this case, the contents of the result
variable, which is equal to number
squared. This function fulfills its role by multiplying the input value by itself and returning the result.
The above function definition, by itself, accomplishes nothing. In order for it to be useful, it must be put to work. The following example shows how to use our new square
function:
x = 5; y = square (x);
The first command assigns a value of 5 to the variable x
. The second command uses x
's value, still 5, as a parameter to the square
function. The value returned by the function, 25, is then assigned to the variable y
.
Objects are the core component of JavaScript. Simply stated, an object is an aggregation (i.e., collection) of variables and functions. Ideally, the components of an object are put together in such a way that the object represents both the attributes and behavior of some "thing" being modeled in the program.
An object used to represent a stopwatch, for example, might contain a variable to represent hours, another to represent minutes, and another to represent seconds. The stopwatch object might also contain functions that manipulate those values, such as "start ()
" and "stop ()
". In object oriented languages, object variables are called "properties" and object functions are called "methods."
When a web page is loaded, the browser's JavaScript interpreter automatically creates objects for most of the components contained in the document. This includes -- but is not limited to -- objects for the document's forms, images, and hyperlinks. JavaScript programmers can take advantage of the properties and methods of these objects to accomplish a wide variety of tasks.
You cannot fully appreciate what an object is until you have learned more about properties and methods. Please read on.
It is impossible to explain what an object is without explaining what a property is also. Simply put, the variables that makes up an object are called the object's properties. In other words, properties are variables that belongs to an object; thus they are sometimes called member variables. Other than the fact that properties belong to objects, there is little behavioral difference between variables and properties.
Properties have names just like variables do, and in fact follow the same naming rules. However, a property's name alone is insufficient to identify an object's property. This is because properties belong to objects, and the object to which the property belongs must also be specified. In JavaScript, properties are identified by concatenating the object and property names together, with the object name first and the two names separated by a dot (period).
Consider a variable, called "Examples:
time . hours
time . minutes
current_window . width
user . password
user . name . first
*
watch
," whose value is an object that represents a stopwatch. If the properties of watch
are hours
and minutes
, then the program fragment below demonstrates how watch
's properties can be manipulated so that the object represents a time which is 5 minutes later:
/* Increase minutes by 5: */
watch . minutes += 5;
/* If minutes now exceed 59, then subtract 60 and bump the hours by one: */
if (watch . minutes > 59)
{
watch . minutes -= 60;
watch . hours += 1;
}
As you can see, properties are treated just like normal variables. From this point of view, properties are like variables with long, dotted names. On the other hand, you shouldn't forget that properties are components of their objects, and that the objects themselves are also variables.
Although the code shown above accomplishes what it is supposed to do, it has a serious limitation: it works only on a stopwatch object named "watch
". If we were using multiple stopwatch objects to represent the times of several participants in a race (such as "watch1
" and "watch2
"), we would have to duplicate the code once for each object, changing the object name "watch
" to the name of the new object in each replication.
This is more work than most programmers are willing to do. The object-oriented answer to this problem is a special kind of function call a method. Methods are functions that belong to objects, and for that reason they are sometimes called "member functions." Member functions are designed to operate directly on the properties of the object to which they belong.
Let's rewrite the previous sample code as a member function. Creating member functions requires two steps. First, we define a generalized function that does not apply to any object in particular:
// Step 1: function update_by_5 () { this . minutes += 5; if (this . minutes > 59) { this . minutes -= 60; this . hours += 1; } }
The JavaScript interpreter recognizes the word "this
" as a synonym for "the object to which I belong." Since at this point the update_by_5
function doesn't actually belong to an object, the concept of "this
" doesn't have much meaning. Step 2 provides the cure for this problem:
// Step 2: watch . update = update_by_5;
This assignment statement tells the interpreter to let update
be a member function of the watch
object. It says that update
's behavior should be the same as specified for update_by_5
.
Now that watch
has an update ()
method, we can invoke it with the following statement:
watch . update ();
This statement tells the JavaScript interpreter to run the update_by_5
function with the word "this
" replaced by "watch
". As a result, watch
's member variables, hours
and minutes
, will be replaced with values that represent a time that is 5 minutes later.
If there are other stopwatch objects, the update_by_5
function can be attached to them as well. There is no practical limit on the number of objects to which a single function can be attached.
Variables, functions, objects, properties, and methods are the major players in JavaScript programs. If you have understood the definitions contained in this article, then you are well on the road to JavaScript enlightenment. :-) The next thing you should do is consult Netscape's JavaScript Guide. This guide contains invaluable information about variables, functions, objects, properties, and methods that are automatically available in every running JavaScript program. Good luck!
Charlton Rose
May 21, 1997