Reputation: 6310
Let's assume I have the following CoffeeScript code:
person =
name: 'Alice'
Now, I want to augment this object with two additional properties. The common way is to write:
person.age = 34
person.bestFriend = 'Bob'
However, I don't like repeating person
. What I do like however, is writing:
person =
age: 34
bestFriend: 'Bob'
(Unfortunately) This creates a whole new object and assigns it to the person variable, meaning Alice has lost her name. Is there a nicer way to augment an object in CoffeeScript besides writing property assignments line by line? Something like:
person.augment
age: 34
bestFriend: 'Bob'
Upvotes: 1
Views: 59
Reputation: 19229
Not as a language feature, but writing a simple extend
function is easy enough (or use an existing version on Underscore or jQuery):
extend = (dst, src) ->
dst[k] = src[k] for k of src
dst
person =
name: 'Alice'
extend person,
age: 34
bestFriend: 'Bob'
Upvotes: 2