July 2005 Archives

Another practical use for JavaScript closures

| 2 Comments

Vincenzo Alcamo wrote to me with another practical use for closures in JavaScript. Vincenzo is working on a JavaScript library he calls XMLLib, based on the Sarissa library. To prevent his library from cluttering the global namespace, Vinceno defines his symbols in his own XMLLib namespace, of course.

But he goes one step further. In Vincenzo's code, only publically exported methods and properties ever get stored in the XMLLib object. Internal, helper methods that are not intended for public use exist in a closure, where all the public methods can use them but where they are hidden from everyone else.

Schematically, the code looks like this:

// Create an empty namespace
XMLLIB = {}

(function() {  // anonymous function creates a closure for us
    // Thi s is a private method that stays hidden within the closure
    function private_utilty_method() { /* utility code here */ }

    // This method is exported into the XMLLib namespace, so it is a public method
    // But since it is defined here, it can call private methods like the one above.
    XMLLib.publicMethod = function() { /* ... */}
})();  // Close function definition and invoke it all at once

Contrast this approach to private symbols with that taken by JSAN. In that framework, a namespace may contain a mix of public and private symbols. The namespace also declares an array of symbols that should be exported by default, and an array of symbol that are allowed to be exported from the namespace. Any symbols excluded from these arrays are private, and the JSAN exporter functions will not copy them into the global namespace. That is, the JSAN framework does not have true privacy via closures, but defines a convention which, when followed, provides a measure of privacy.

Thanks for the tip, Vincenzo!

Borrowing methods instead of inheriting methods

| 8 Comments

The typical way to create new classes in JavaScript is by subclassing another class to inherit its methods. It occurs to me that this is not the only way. Since functions are data values in JavaScript, it is also possible to extend a class simply by copying methods from another class into it. I call this "borrowing" (although I suspect that someone else has already named it something else--let me know):

The code at the end of this postdemonstrates. It creates a simple Rectangle class. Then another simple class called GenericToString. This second class isn't good for much on its own, but serves as a "mixin" that can be borrowed by other classes. The next bit of code in the example is a function that does the borrowing. This is followed by a new class Rectangle2, which does nothing of its own, just borrows methods from the first two classes.

Update: I should add here that this method borrowing technique can be compared to multiple inheritance. The Rectangle2 class inherits methods from Object and borrows methods from two other classes. If there was a way of writing abstract methods in JavaScript (perhaps just throw "this method is abstract!") then borrowing methods from a class that defined abstract methods would be a little like implementing an interface in Java.

I'm interested in reader's thoughts on this technique. Is anything like this used in other languages? Has anyone given this an official-sounding name?

The code is in the extended entry...

JavaScript Module Conventions?

| 2 Comments

Unobtrusive JavaScript calls for JavaScript code to be removed from our HTML and placed in external .js files. At the same time, JavaScript frameworks and libraries are multiplying like crazy. More and more, we are going to be seeing web pages that load 2, 3, or more external .js files.

This means that we need to become disciplined about how we create those .js files, and adopt namespace conventions for these external modules of code so that two modules do not overwrite each others properties.

As far as I can tell, each JavaScript framework out there does this slightly differently. The most explicitly documented set of conventions I've seen are Casey West's rules for writing modules that work with his JSAN.use() function Casey's use() function is a perl-influenced function that loads (dynamically!) a .js module and then imports a set of symbols from the module into the global namespace. it is good stuff, but his module-structuring and namespace-creating rules are tied directly to his JSAN.use() code and I don't think they are general enough for people who want to write modules to be statically loaded with a <script> tag.. For example. a JSAN module defines the set of symbols that it can export, but the only way to import those symbols is via the use() function. There is not a separate import() function for importing symbols. without using use().

If you know of a well-articulated set of conventions for defining reusable modules of JS code, putting them in namespaces, and importing symbols, please add a comment to this post!

Here is my first cut at a list of requirements for a JavaScript module system:

  1. A .js module must not define more than one symbol in the global namespace. If it does define a symbol, that symbol should probably be the same as, or derived from, its filename.
  2. Any additional symbols defined by a module should be defined within a separate object, or "namespace".
  3. We need a way to selectively import symbols from a namespace into the global namespace. This is for convenience only; the methods deifned by a module should be written to work from their own namespace or from the global namespace.
    1. We could standardize an import() function for doing this importing. Or just create the necessary conventions, so that different frameworks can create their own import() methods.
    2. Modules should probably be allowed (but not required) to declare their own list of exported symbols (as JSAN modules do). And if such a list is defined, the import facility should not allow non-exported symbolsto be imported.
  4. For client-side programming, modules need a safe way to register code to be run in response to the onload event, without worrying that they will overwrite or be overwritten by the initialization code for some other module.
  5. There should be a standard way for a module to declare its name and version number.
  6. There should be a standard way for a module to register itself as loaded, and a standard way for a module to query the list of loaded modules (to verify that any modles it depends on are already present).

Please feel free to add your own ideas in the comments!

What should we call JavaScript pseudo-classes?

| 6 Comments

Like many others, I use the term "class" to informally describe the things we create in JavaScript using constructors and prototype objects. But JavaScript 2.0 is on the horizon, and since that version of the language has real classes, I want to start using a different term to describe JavaScript 1.x pseudo-classes.

Is anyone aware of a pre-existing convention that I can adopt? I've tried using "category" but I think it is too vague. My current feeling is that I should use the hypenated word "proto-type", although if I do this, I need to be careful not to confuse it with "the prototype object" that we use to create a proto-type.

If you have a thought or better suggestion, I'd love to hear about it. Just retaining our current usage of "class" is an option, too, of course.

Find the JavaScript bug

| 3 Comments

Can you spot the bug in the following code?

// Compute the sum of the elements in array a
function sum(a) {
    // Bonus feature: if we're passed more than one argument,
    // then sum the arguments of the array instead.
    if (arguments.length > 1) a = arguments;
    var total = 0;
    for(var i = 0; i < a.length; i++) total += a[i];
    return total;
}

Hint: the function works correctly if you pass an array, but not if invoked with more than one argument.

Answer follows...

Another Useful JavaScript Closure

| 9 Comments

I found another useful example involving closures. Bob Ippolito's python-style iteration framework includes this nifty code:

arrayLikeIterator = function (arrayLike) {
    var i = 0;
    return {
        'next': function () {
            if (i >= arrayLike.length) {
                throw StopIteration;
            }
            return arrayLike[i++];
        }
    };
};

There is lots more to Bob's iteration framework at his blog. The iteration stuff is part of Bob's larger framework, MochiKit, which looks quite interesting.

For the record, I disagree with Bob about throwing an exception at the end of iteration. I tihnk he'd be better of returning a unique sentinel value (but probably not null). His StopIteration error object could work just fine as a sentinel, if he'd return it instead of throwing it.

Update: after exchanging a number of emails with Bob, I now understand that his iterators are python-style iterators, intended to be used as part of a larger framework, and that they are to be treated as opaque values and passed to other functions that do the work of iterating them. That is, the end user of the iterators never has to catch the exception that the iterator throws. Bob has convinced me when an iterator is processed by a chain of composed functions, the use of an exception to end the iterator is the most efficient way to go. So, I drop my objection to throwing an exception to end iteration, as long as you use Bob's iterators in the python-based style he intends.

JavaScript Closures Example

I came up with the code below to demonstrate that two JavaScript closures can have the same scope chain. This gives them shared access to properties that are not accessible from anywhere else.

Here's the code:

//
// This function adds property accessor methods for a property with 
// the specified name to the object o.  The methods are named get<name>
// and set<name>.  If a predicate function is supplied, then the setter
// method uses it to test its argument for validity before storing it.
// If the predicate returns false, then the setter method throws an exception.
// 
// The unusual thing about this function is that the property value 
// that is manipulated by the getter and setter methods is not stored in
// the object o.  Instead, the value is stored only in a local variable
// in this function.  The getter and setter methods are also defined
// locally to this function, and therefore have access to this local variable.
// Note that the value is private to the two accessor methods, and it cannot
// be set or modified except through the setter.
// 
function makeProperty(o, name, predicate) {
    var value;  // This is the property value

    // The setter method simply returns the value
    o["get" + name] = function() { return value; }

    // The getter method stores the value or throws an exception if
    // the predicate rejects the value
    o["set" + name] = function(v) { 
        if (predicate && !predicate(v))
	    throw "set" + name + ": invalid value " + v;	
	else
            value = v;
    }
}

// The following code demonstrates the makeProperty() method 
var o = {};  // here is an empty object

// Add property accessor methods getName and setName()
// Ensure that only string values are allowed
makeProperty(o, "Name", function(x) { return typeof x == "string"; });

o.setName("Frank");  // Set the property value
print(o.getName());  // Get the property value
o.setName(0);        // Try to set a value of the wrong type

This example is simlar to Douglas Crockford's Private Members in JavaScript.

I don't think it is actually that useful in practice--I don't recommend that anyone start calling my makeProperty() function on their own objects! As far as I know, the most realistically useful application of JavaScript closures is Steve Yen's breakpoint() function.

WaSP tackles JavaScript

I've been turning my attention from Java to JavaScript in recent days.

I discovered this morning that the Web Standards Project (or WaSP) has turned its attention to JavaScript, as well. They have recently announced the launch of the DOM Scripting Task Force to promote "unobtrusive" JavaScript programming using the W3C DOM. See the Manifesto and their Definitions. There is not much else at the task force's site yet. Here's an interesting example of unobtrusive JavaScript in action, however.

If WaSP can do for JavaScript programming what they have done for CSS, this is a great thing for the web!

J2SE is Dead. Long Live Java SE!

I got email today from the JCP. JSR-270 (the umbrella JSR for Java 6) has changed its name:

The Spec Lead of the following specification

   JSR-000270 J2SE 6.0 ("Mustang") Release Contents

has updated the name of the JSR to be

   JSR-000270 Java SE 6 ("Mustang") Release Contents

The 2 is finally gone! J2SE is now "Java SE"!

Careful with SortedSet comparators

Reader Guohong Liu wrote to me to point out a bug in my book Java Examples in a Nutshell.. The bug is with example 4-6 whch is an example of using threads to implement the java.util.Timer class. The particular details aren't interesting, but the overall cautionary tale is.

In this example, I use a java.util.TreeSet to maintain a list of TimerTask objects sorted in execution order. What I forgot is that the SortedSet interface uses the comparator to determine object equality as well as ordering. When there were two TimerTask objects with the same scheduled execution time, my compartor returned 0 to indicate that I didn't care about the order of these two objects.

In fact, what happened in this case is that the TreeSet treated the two task objects as equal in the sense of the equals() method. And, since it is a set, after all, it only allowed one of the objects to be inserted. One task would get lost and never be executed.

So, if you want to use a SortedSet to implement a sorted list, as I did, it is not sufficient to simply rely on the identity-based Object.equals() method. You have to code your compareTo() method or your Comparator object carefully so that they only return 0 if the objects being compared are in fact the same object.

This is all clearly spelled out in the SortedSet javadoc. The sorting order must be "consistent with equals()". My class inherited the identity-based equals() method from Object. But my comparator could return 0 even when equals() would return false for the same two objects.

Books

Comprehensive coverage of Ruby 1.8 and 1.9

"The New Most Important Ruby Book"
Peter Cooper,
rubyinside.com

Completely updated for Ajax and Web 2.0

"A must-have reference"
Brendan Eich,
creator of JavaScript

The classic Java quick-reference