T.J. is correct, of course, that my original suggestion would make
multiple copies of the functions.  That's what I get for writing off
the top of my head.   If I understand correctly, what joe t. really
want is something like:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
var specialDateFactory = function () {
        var calcIsEaster = function () {
                // do something with _this_, which will be a Date object
                this.isEaster = true;   // replace with real code

        var calcIsLaborDay = function () {
                // do something with _this_, which will be a Date object
                this.isLaborDay = false;   // replace with real code

        return function () {
                var that = new Date();

                that.calcIsEaster = calcIsEaster;

                that.calcIsLaborDay = calcIsLaborDay;

                return that;
} ();

var myDate = specialDateFactory();
document.write("<p>myDate.isEaster: " + myDate.isEaster + "</p>");
document.write("<p>myDate.calcIsLaborDay: " + myDate.calcIsLaborDay +
document.write("<p>myDate instanceof Date: " + (myDate instanceof
Date) + "</p>");

The factory function specialDateFactory returns a Date instance which
has methods calcIsEaster and calcIsLaborDay, and properties isEaster
and isLaborDay.  If you change the value of the returned object, you
can call calcEaster and calcIsLaborDay again to refresh .isEaster
and .isLaborDay.

What's more, the functions like calcIsEaster and calcIsLaborDay can
call each other securely -- no matter how objects returned from
specialDateFactory are abused, variables in the closure are
undisturbed.  So you can securely add lookup tables and helper
functions hidden from the outside.

And this introduces only one closure, so it's fairly cheap.

JavaScript constructors are an anomalous, pseudo-classical things.
If you're not going to compare objects with instanceof, don't bother
with them.  More often, factories are what you really want.
You received this message because you are subscribed to the Google Groups 
"Prototype & script.aculo.us" group.
To post to this group, send email to prototype-scriptaculous@googlegroups.com
To unsubscribe from this group, send email to 
For more options, visit this group at 

Reply via email to