January 12, 2000 - Constructor Functions | WebReference

January 12, 2000 - Constructor Functions

Yehuda Shiran January 12, 2000
Constructor Functions
Tips: January 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

A constructor function defines the object's properties and methods. Here is an example for a constructor function that accepts three parameters and defines four properties (id, posY, width, and show) and three methods (makeImage, makeElement, and showElement):

function popout(id, posY, width) {
  this.id = id; // the element's name (and the variable name)
  this.posY = posY; // the element's top property
  this.width = width; // the element's width
  this.show = false; // do not show the element
  this.makeImage = makeImage; // constructs the image's tab
  this.makeElement = makeElement; // constructs the content box
  this.showElement = showElement; // sets the element visibility
}

A pop-out element is defined as an instance of the popout object:

var variableName = new popout("variableName",
                              topDistance,
                              elementWidth);

Note that the name of the variable must be the same as the string passed to the function. For example:

var myEl = new popout("myEl", 500, 150);

In general, the new instance variableName features the following properties and methods:

variableName.id
variableName.posY
variableName.width
variableName.show
variableName.makeImage()
variableName.makeElement()
variableName.showElement()

Notice that the constructor function, popout(), must define the methods as function references. Therefore, the method names are not followed by a set of parentheses. It is very important to understand the difference between a function call and a function reference. A function call simply invokes a given function, whereas a function reference is actually an object representing the function. The following script demonstrates the difference:

function displayAlert() {
  alert("This is a function.");
}
displayAlert(); // a function call
var equivFunction = displayAlert; // a function reference
equivFunction(); // a function call

A function reference is just like any other object. In this example, displayAlert (not displayAlert()) is a reference of the function, so it can be assigned to a variable. That variable then refers to the function, so it can be invoked just like the original function.