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
.
Posted by Henning Koch to makandra dev (2013-06-13 08:47)