jashkenas/coffee-script — Issue #1984: Fat-arrow syntax for instance-bound method declaration is inconsistent. #enhancement #discussion
Author: jaekwon
Created: 2011-12-29 01:01:56+00:00
State: open

Currently, as we all know, this is how you declare instance-bound methods in CoffeeScript:

```coffeescript
class Foo
method: => "#{this} is an instance of Foo."
```

I think this is confusing because `this` normally refers to the class (`Foo`) in the class declaration scope.
That is, `: =>` is special. This is a leaky abstraction that causes problems with metaprogramming and decorators…

```coffeescript
class Foo
this::["dynamicMethod"] = (args…) => … # this function is bound to Foo, not the instance.

myDecorator = (fn) -> fn # dummy decorator

class Bar
method: myDecorator => … # this function is bound to Bar, not the instance.
```

I looked through the CoffeeScript source and grammar rules to figure out how I might branch CoffeeScript to make instance-bound methods more consistent. I thought maybe a one way might be to add a new syntax for object key assignment + binding…

```coffeescript
class Foo
method:= myDecorator -> "The := means assign value to key AND bind value to the object."

# also works on objects as expected:
myObject =
key1: "value1"
key2: "value2"
key3:= (args...) -> "This is also bound to myObject"
```

… but this still requires compile-time analysis, so it wouldn't work for metaprogramming.

I managed to figure out a way that involves a custom Base class, which I'll be using for now: https://github.com/jaekwon/Cardamom/blob/master/src/base.coffee. Decorators work, and metaprogramming too, but it does sidestep the way methods are bound during the constructor, and there may be performance penalties.

Thoughts?