Coffeescript: Caveat when cloning objects with fat-arrow methods

Posted Almost 11 years ago. Visible to the public.

Coffeescript allows you to create classes whose methods are automatically bound to the correct this. You can do this by using a fat arrow:

class Person

  constructor: (name) ->
    @name = name

  sayHello: =>
    alert("Hello, I am #{@name}")

An important caveat is that when you clone such an object, all of its methods are still bound to the original instance:

eve = new Person("Eve")
eve.sayHello() # => "Hello, I am Eve"
bob = _.clone(eve)
bob.name = "Bob"
bob.sayHello() # => "Hello, I am Eve"

I don't think there is a workaround for this, you simply cannot clone instances of Coffeescript instances as you would clone other Javascript hashes. If you need cloning, you would probably need to implement a clone() method in your class, which constructs the clone instance using new.

Henning Koch
Last edit
Over 7 years ago
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2013-06-13 08:47)