Posted about 7 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:

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

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Henning Koch
Last edit:
7 months 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