Posted over 6 years ago. Visible to the public.

Coffeescript: Caveat when cloning objects with fat-arrow methods

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

Copy
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:

Copy
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.

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Avatar
Henning Koch
Last edit:
17 days ago
by Besprechungs-PC
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more