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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)