jashkenas/coffee-script — Issue #1767: name functions via the displayName property
Author: pmuellr
Created: 2011-10-11 11:39:15+00:00
State: open

There is a convention used by at least the following debuggers to allow anonymous functions to be named by the source code:

* [Web Inspector](http://developer.apple.com/library/safari/documentation/appleapplications/Conceptual/Safari_Developer_Guide/OptimizingYourWebsite/OptimizingYourWebsite.html)
* [FireBug](http://code.google.com/p/fbug/issues/detail?id=1811)
* [weinre](http://phonegap.github.com/weinre/)

The convention is that a function which otherwise doesn't have a `name` property which is a string, will be checked to see if it has a `displayName` property, and that will be used in lieu of the name. The convention was originally added to Web Inspector by the Objective-J developers.

I would like this support added to CoffeeScript as a new option of the coffee compiler.

There's less need for this today, with the JS engines doing name inferencing for anonymous functions, but not all JS engines support this. In addition, the JS engines that weinre supports (eg, on mobile devices) are typically older than their desktop brethren, and are less likely to have that support.

Even with name inferencing, some folks might prefer a slightly cleaner look.

Proposal:

* new command line option `-f` which will add the displayName property to every function CoffeeScript produces, except for constructors which are already named.

* I see 4 forms of functions, which would presumably have different naming styles:

* static methods of a class: `(className)::(methodName)`
* instance methods of a class: `(className).(methodName)`
* functions in a class: `(className):(functionName)`
* functions not in a class: `(functionName)`

I'm not married to the choice separators in the names, that was just my initial thought.

Methods in a class should be babycakes; functions will be harder, and I don't have a sense for how much harder. Certainly, there are cases where there is no obvious name, and those functions should be left anonymous.

Here's an example.

CoffeeScript:

````coffee
class X
@a: () -> a
b: () -> b
c = () -> c

d = () -> d
````

JavaScript produced today:

````js
var X, d;
X = (function() {
var c;
function X() {}
X.a = function() {
return a;
};
X.prototype.b = function() {
return b;
};
c = function() {
return c;
};
return X;
})();
d = function() {
return d;
};
````

JavaScript produced tomorrow with the -f option:

````js
var X, d;
X = (function() {
var c;
function X() {}
X.a = function() {
return a;
}; X.a.displayName = "X::a"
X.prototype.b = function() {
return b;
}; X.prototype.b.displayName = "X.b"
c = function() {
return c;
}; c.displayName = "X:c"
return X;
})();
d = function() {
return d;
}; d.displayName = "d"
````