Read more

Coffeescript: Caveat when cloning objects with fat-arrow methods

Henning Koch
June 13, 2013Software engineer at makandra GmbH

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}")
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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.

Posted by Henning Koch to makandra dev (2013-06-13 10:47)