Jake Wilson
Jake Wilson

Reputation: 91203

How to add method to existing object in Coffeescript?

Lets say an object is created by some function:

myObject = someFunction();

So now, myObject is an object.

How do I add a new method to this object? The following does not work in Coffeescript:

myObject.newMethod: (something) ->
  # do stuff here

I am not able to edit the object definition in someFunction(), so I have to add the method to the object after the fact. What is the proper syntax here?

Upvotes: 1

Views: 490

Answers (1)

Brigand
Brigand

Reputation: 86250

It would be myObject.newMethod = (something) ->.

You use the colon when declaring a property, and the assignment operator when assigning to a property. The only time you declare a property, is when the object is being created. This is also true in JavaScript.

var myObject = {foo: 'bar'}; 
myObject.baz = 'quux';

The best practice is to not modify objects you don't own (someFunction owns that object). You should instead create a function which takes that kind of object as an argument.

Upvotes: 6

Related Questions