Like most object-oriented languages, JavaScript supports the notion of object ‘constructors’ (special procedures for creating objects). You’ve seen these, no doubt, in the form of JavaScript’s built-in constructors for things like Strings and Functions. The String constructor takes a string-literal as an argument:
var str = new String('This is the argument.');
Notice the ‘new’ keyword, which is a tipoff to the fact that String() is a constructor.
It hands back a String object, with all due methods and properties appertaining thereto.
But did you know you can create your own constructors (for custom object types) in
JavaScript? It’s a straightforward process. The one thing that may seem unfamiliar is the
special meaning of the ‘this’ label in a constructor context.
An Example
Suppose we want to create an object class called Circle. The members of this class will
have built-in properties of name, cx and cy (center-point coordinates),
radius, and a method called inside(), which returns true if a given point is
inside the circle and false if it falls outside the circle. The constructor looks like:
function Circle(name) {
this.name = name;
this.cx = 0.0;
this.cy = 0.0;
this.radius = 0.0;
this.inside = new Function(' 'var a = arguments[0]; 'var b = arguments[1]; 'var radix = (this.cx-a)*(this.cx-a)+(this.cy-b)*(this.cy-b); 'return ( Math.sqrt(radix)< this.radius)?true:false;');
}
To use this constructor to create a Circle object, then manipulate the object’s
properties and use its inside() method, you might do:
'var c = new Circle('Plain'); // create a circle named Plain
c.radius = 9.0; // its radius is 9
c.cx = 1.0; // set it at 1,1
c.cy = 1.0;
app.alert( c.inside(3,4) ); // displays 'true'
app.alert( c.inside(13,4) ); // displays 'false'
c.cx = 7.0; // move it over a bit...
app.alert( c.inside(13,4) ); // displays 'true'
How it works
Here’s how the constructor works. In JavaScript, if you place ‘new’ in front of a
function name, the function gets handed (in its ‘this’ object) a newly created, generic
Object. The function can do whatever it wants to this object, in terms of adding properties
and/or methods. We added several properties (cx, cy, radius) along with a custom method,
which we created internally using the Function constructor, assigning it to the name
inside. Thus, inside() becomes a method available to Circle objects. Before
our constructor finishes, it hands back the ‘this’ object to the caller, who can manipulate
it as needed.
You may or may not ever need to create your own custom object classes with custom
constructor functions, but it’s good to know the capability exists, if you need it. It’s a
sophisticated bit of functionality if used right. Kind of like having most of the power of
C++… without the 1000-count bottle of Ibuprofen to go with it.
For more info on constructor functions and how to work with them, consult any good
JavaScript text (my favorite being David Flanagan’s JavaScript: The Definitive
Guide).