December 17, 1999 - Passing by Reference vs Passing by String | WebReference

December 17, 1999 - Passing by Reference vs Passing by String

Yehuda Shiran December 17, 1999
Passing by Reference vs Passing by String
Tips: December 1999

Yehuda Shiran, Ph.D.
Doc JavaScript

Objects are created in JavaScript in various ways. The new constructor returns a pointer to a new object:

var a = new Layer();

Another way to create an object is to specify it in an HTML tag:

<OBJECT ID="kuku">blabla</OBJECT>

When an object is identified by its pointer, we pass it around by reference. When the object is identified by its ID string, we pass it around by string. You can check if an element is passed by reference or by string, by simply printing it to an alert box. The object passed by reference will be printed as an object, while the one passed by string will be printed as a string.

Let's take an example that shows the differences between call-by-reference and call-by-string. The function setVisibility() sets the visibility of a passed-by-string element:

function docjslib_setVisibility(id, flag) {
  if (NS4) {
    var str = (flag) ? 'show' : 'hide';
    eval("document." + id).visibility = str;
  }
  else {
    var str = (flag) ? 'visible' : 'hidden';
    eval("document.all." + id).style.visibility = str;
  }
}

The following function sets the visibility of elements that are passed by reference (objects):

function docjslib_setElementVisibility(id, flag) {
  if (NS4) {
    var str = (flag) ? 'show' : 'hide';
    eval(id).visibility = str;
  }
  else {
    var str = (flag) ? 'visible' : 'hidden';
    eval(id).style.visibility = str;
  }
}

You can learn more about passing objects by reading Column 33, DOCJSLIB Version 4.0: Scrollers, Watermarks, and Games.