jashkenas/coffee-script — Issue #1966: Leaky abstraction in dynamically assigned constructor functions
Author: jnicklas
Created: 2011-12-23 20:45:23+00:00
State: open

So to my delight, I discovered that CoffeeScript does handle the case of assigning a function to the magic `constructor` property on CoffeeScript classes. However, I discovered that this is somewhat of a leaky abstraction.

In JavaScript, the return value of the constructor function matters. If an explicit return is used and that return returns an object (as opposed to a a "primitive" such as a string), then that object is returned. When a function is given explicitly to the `constructor` property, this works as expected in CoffeeScript, however, when the function is dynamically assigned, it does not.

This is an example:

``` coffeescript
class Foo
constructor: ->
return { foo: 'foo' }

class Bar
ctor = -> return { foo: 'foo' }
constructor: ctor

new Foo().foo // => "foo"
new Bar().foo // => undefined
```

Here we would expect both `new Foo()` and `new Bar()` to return the same result, but they do not.

I spent some time thinking about this, and my thinking is that given the constraints of CoffeeScript, this problem is impossible to fix, and I will probably just have to live with it. I realize this is a pretty weird edge case. Still wanted to write it down here in case it's of interest to anyone.