Object-Oriented Programming with JavaScript, Part II: Methods: Enforcing Object Construction - Doc JavaScript | WebReference

Object-Oriented Programming with JavaScript, Part II: Methods: Enforcing Object Construction - Doc JavaScript


Object-Oriented Programming with JavaScript, Part II: Methods

Enforcing Object Construction

The following code includes a mistake. Can you find it?

function Employee(a) {
  this.name = a;
}
function init(){
  John = Employee("Johnson");
  alert(John.name);
}

You guessed it right. The code is missing the keyword new before the constructor name Employee. The correct code for init() is:

function init(){
  John = new Employee("Johnson");
  alert(John.name);
}

Calling the first init() above will give an error. One defensive programming action would be to add a check inside the constructor. It will match the calling object (this) with the constructor class (Employee) by the following check:

(this instanceof Employee)
If this check fails, we call the constructor again, this time without forgetting the keyword new. The constructor function Employee becomes:

function Employee(a) {
  if (!(this instanceof Employee)) return new Employee(a);
  this.name = a;
}
function init(){
  John = Employee("Johnson");
  alert(John.name);
}

Try calling init(). You will not get an error, because we create the object for you.

Next: How to distinguish between private and public data elements


Produced by Yehuda Shiran and Tomer Shiran
All Rights Reserved. Legal Notices.
Created: March 26, 2001
Revised: March 26, 2001

URL: http://www.webreference.com/js/column80/7.html