February 15, 2000 - Creating Objects | WebReference

February 15, 2000 - Creating Objects

Yehuda Shiran February 15, 2000
Creating Objects
Tips: February 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

One of the first topics you need to learn when learning a new language is how to allocate memory for your data structures. In JavaScript, the operator new is the memory allocator which you would use in conjunction with creating new objects. All intrinsic JavaScript objects begin with a capital letter. For example, in order to create a new array of length 9, you would write the following:

arr = new Array(9);

Here's an example of how to create a constructor function:

anim1 = new animation("ball1");

where animation is a user-defined function. Here is an example:

function animation(id) {
  this.element = (NS4) ? document[id] : document.all[id].style;
  this.active = 0;
  this.timer = null;
  this.path = null;
  this.num = null;
  this.name = id + "Var";
  eval(this.name + " = this");
  this.animate = animate;
  this.step = step;
  this.show = show;
  this.hide = hide;
  this.left = left;
  this.top = top;
  this.moveTo = moveTo;
  this.slideBy = slideBy;
  this.slideTo = slideTo;
  this.circle = circle;

Notice the usage of the this prefix which gives you a reference to the object's father.

Learn more about memory allocation in Column 18, JavaScript Animation, Part I.