Chapter 12
Building and Extending Objects
Creating Instances
Objects are templates by which you create instances. For example, suppose
you have defined an employee object that includes some methods and properties of an
employee, such as his or her social security number and address. This definition has no
effect on the script, because no new entity has been changed or created. Only when you
apply the object’s definition to a specific person, say John Doe, is a new entity
created—an instance of that object. The number of instances you create with a single
object definition is unlimited. The object definition can be either one you define with a
function, or a built-in one. Creating an instance of a built-in object is relatively
simple because the object is predefined. As you will see later, you can extend an existing
object by adding new properties and methods to it.
You should use the following syntax to create an instance:
var name = new constructorFunction([arguments])
So, if you want to create an instance of the String object, you can use the
following statement:
var str1 = new String("Hello!")
This statement creates an instance named str1. You can create another instance
if you like:
var str2 = new String("Hi!")
The instances str1 and str2 act similarly to regular variables. You
can pass them on to functions as in:
function printValue(val) {
document.write("*** " + val + " ***")
}
printValue(str1)
You can also return objects:
function printValue(obj) {
return obj
}
Remember that if you create an instance of an object inside a function, it is
considered local, i.e., it is visible only inside the function during the function’s
current execution course. If you declare the instance outside a function, it is preferable
that you use the var keyword. When you create an instance of an object inside a
function without var, it is a global structure. Bear in mind that if you create a
global instance, or even a simple variable inside a function, you must execute the
function before that global data structure exists in the script. From that point on you
can refer to it freely anywhere in the document.
When you create an instance of an object via the new operator, you are
actually declaring a specific data structure according to the object’s definition. All
properties referenced in the constructor function are accessible as properties of the
object’s instance.
Note that object definitions (constructor functions) do not take up any memory, because
they are abstract units. However, instances are data structures so they do require some
RAM space, depending on their exact structure and data.
After you have created an instance of an object, you do not have to use the keyword new
anymore when referring to that instance. However, if you want one of the instance’s
properties to be an instance of its own, you must use new again to create the new
object.
An instance of an object also features its methods. Each instance has a reference to
the function playing the role of that method. You do not have to worry about this, because
when you refer to the instance’s method, you only specify the name of that method. The
reference is already defined in the constructor function, so it invokes the corresponding
function.
Take a look at the following example:
var current = new Date() // the current date
var minutes = current.getMinutes()
var current2 = new Date() // the current date
var minutes2 = current2.getMinutes()
As you can see, both instances have methods. A method belongs to a specific instance
but not to the general object. Sometimes two different instances of the same object do not
have the same methods and properties. This happens when the constructor function includes
a conditional statement to determine which methods should be applied to the current
instance being defined, or when a single instance of an object is modified afterwards.
Note: An object is an abstract definition, whereas an instance is a
data structure defined according to an object. Therefore the term “object” differs
from “instance.” However, instances are commonly referred to as objects. It should be
very clear where the term “object” refers to an instance. In this book we often refer
to instances as objects, so do not be confused.
Constructor Functions
As you learned earlier, JavaScript supports functions that build custom objects. In
order to create such functions you must know how to define properties and methods. A constructor
function is a simple function that defines the properties and methods of the relevant
object type. You can think of built-in objects as objects whose constructor functions are
predefined in JavaScript, so you do not need to write them on your own.
A constructor function resembles a cookie cutter. You provide it some dough and it
gives the dough the proper shape. The cookie cutter is like the constructor function
because they both receive a simple structure and change it according to a specified
template.
Defining Object Properties
The keyword this is probably the most important word related to objects in
JavaScript. It refers to the current object, or instance. Inside a constructor function it
refers to the instance for which the function was called. Take a look at the following
function:
function student(name, age, avgGrade) {
this.name = name
this.age = age
this.grade = avgGrade
}
This function accepts three arguments. It defines an object type of a student in a
class. The properties are name, age, and grade, and they are
initialized by the values passed on to the function. You can use the following statement
to create an instance of this object—a student in a class:
var student1 = new student("Sharon", 16, 85)
Figure
12-1. A simple message built according to the properties of
the object.
Now you can refer to these properties in the following fashion:
alert(student1.name + " is a cute " + student1.age + " - year old.)
It is also possible to add properties to an object once it has been created. Such
properties exist only in the specific instance to which they are assigned. The following
script segment demonstrates this: