small medium large xlarge

Back to: All Forums  CoffeeScript
Generic-user-small
08 Feb 2012, 20:28
Ken Burgett (22 posts)

I am confused over the syntax of function definitions. Why are some functions defined with a colon and some with an equal sign? It appears that the ‘:’ is used in functions within classes, but I can’t find any rationale for that. I am quite confused by this.

Trevor_burnham__goofy_headshot__pragsmall
09 Feb 2012, 16:19
Trevor Burnham (54 posts)

Functions are just like any other objects in JavaScript: They can be assigned to a variable with @=@, or attached to an object with @:@.

In the body of a class, @a = b@ means “I’m assigning @b@ to a variable named @a@ scoped within this class body,” and @a: b@ means “I’m assigning @b@ to the @a@ property of this class’ prototype.”

Hope that helps! Remember that you can always plug code into the “Try CoffeeScript” panel at http://coffeescript.org/ to see how it translates into JavaScript.

Generic-user-small
14 Feb 2012, 18:52
Ken Burgett (22 posts)

Thanks for the clarification, Trevor. I am a rubyist, but have no experience with Javascript, so, a couple of things caught me out:

1) In Ruby the ampersand prefixes class variables, while instance variables have no prefix. I am used to referencing instance variables that way, because Ruby associates them with the class instance context ‘under the covers’. In JS, there are no covers, everything attached to a class instance must explicitly use ‘this’ or ampersand in CoffeeScript. First gotcha.

2) In Ruby, a class public interface is a set of methods, no other internal data structures are visible. In JS, attributes and functions are both attached to ‘this’, so instance attributes can be accessed by , looking just like a function with no parameters. Second gotcha.

Thanks for the ‘Try CoffeeScript’ url, it is extremely useful.

You must be logged in to comment