March 25, 2001 - Defensive Programming
![]() |
March 25, 2001 Defensive Programming Tips: March 2001
Yehuda Shiran, Ph.D.
|
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. Calling init() will give an error. One defensive programming action would be to add a check inside the constructor. It will match the calling object with the constructor class, and will call the constructor (with new this time), to create the object:
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 never get an error, because we create the object for you, even if the calling code doesn't.


Find a programming school near you