Introducing CoffeeScript
Objects
As I wrote above, everything in JavaScript (and, thus, in CoffeeScript) is an object, and every object has properties. (Another way to think about this is to say that everything in JavaScript is a hash, with key-value pairs.) Understanding and working with this can be a bit confusing at first, particularly because of the way the "this" keyword operates. CoffeeScript offers several solutions to this problem, as well as the scoping and variable issues that drive JavaScript programmers crazy.
First, scoping of all variables is lexical and is obvious from the indentation. You can attach variables to the global object, or other objects, but you will end up doing this only when you want, not by mistakenly forgetting to add a "var" somewhere.
Second, properties can be accessed and assigned to as if they were variables, using Ruby-style @varname syntax. So, when you say x=5 in a CoffeeScript program, you're assigning the value 5 to the lexical value x. When you say @x=5 though, you're assigning the value 5 to the property x on the current object.
Finally, "this" is scoped dynamically in JavaScript, changing value to reflect the object to which the current function is attached. This means that if you aren't careful, you can write callback functions that reference "this", but accidentally end up referring to the wrong object. CoffeeScript lets you define functions not only with -> (the "thin arrow"), but also with => (the "fat arrow"). The difference is that when you define functions with =>, they are bound to the value of "this" when it was defined, allowing access to the defining context's properties using @propname syntax.
All of these things come together in CoffeeScript's object model, which extends JavaScript's such that you can work with something resembling a traditional class-instance model, rather than the built-in, JavaScript-style prototype-based model. Prototypes still exist and work—and indeed, CoffeeScript's classes compile into JavaScript prototypes. But, you can get beyond prototype-style inheritance by declaring classes with a constructor. Here is a simple example of the sort of thing you can do:
class Person constructor: (firstName='NoFirst', lastName='NoLast') -> @firstName = firstName @lastName = lastName Person.count++ @count: 0 p1 = new Person() console.log p1 console.log Person.count p2 = new Person('Reuven') console.log p2 console.log Person.count p3 = new Person('Reuven', 'Lerner') console.log p3 console.log Person.count
When you run the above file, you get the following output:
{ firstName: 'NoFirst', lastName: 'NoLast' } 1 { firstName: 'Reuven', lastName: 'NoLast' } 2 { firstName: 'Reuven', lastName: 'Lerner' } 3
This not only shows how you can use CoffeeScript classes in a way similar to traditional classes, but also that you can have default values for function parameters by declaring their values before the -> sign. You also can see how naturally the use of the @propname syntax fits into this object model. The above constructor looks almost like a Ruby method, rather than a JavaScript one, with a clear distinction between local variables and instance variables.
Conclusion
CoffeeScript is an attractive, new language that makes JavaScript programming fun and easy. You can think of it as JavaScript with a new syntax or as an easy-to-learn language that integrates into JavaScript applications, with many ideas taken from Python and Ruby. It removes many of the syntactic bloat and issues associated with traditional JavaScript, simultaneously providing a language that's easier to write and maintain, but also faster to execute, than raw, unoptimized JavaScript. CoffeeScript is a language we all should watch in the coming months and years. It probably won't replace JavaScript altogether, but it definitely will make it easier to accomplish certain tasks.
Next month, I'll look at how CoffeeScript can be integrated into your browser-side Web applications, especially those using jQuery. That's the direction the Ruby on Rails community seems to be moving toward with its 3.1 release, and even if your favorite framework doesn't adopt CoffeeScript, understanding how they work together probably will be useful.
Resources
The home page for CoffeeScript, including documentation, quick references, FAQs and annotated source code, is at http://jashkenas.github.com/coffee-script. There is an active and growing community of CoffeeScript users, with an IRC channel (#coffeescript) and Wiki at GitHub.
For a good introduction to CoffeeScript, see the presentation written by Jacques Crocker, available at http://coffeescript-seattlejs.heroku.com.
Finally, the Pragmatic Programmers have released (at the time of this writing) an excellent pre-release "beta book", written by active CoffeeScript user Trevor Burnham. If you're interested in learning more about this interesting little language, I highly recommend this book. It's mostly aimed at beginners, but given the limited number of advanced CoffeeScript programmers out there, this should not bother you.
- « first
- ‹ previous
- 1
- 2
- 3
Senior Columnist, Linux Journal
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Sponsored by AMD
If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.
Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.
Sponsored by ActiveState
Web Development News
Developer Poll
| Non-Linux FOSS: libnotify, OS X Style | Jun 18, 2013 |
| Containers—Not Virtual Machines—Are the Future Cloud | Jun 17, 2013 |
| Lock-Free Multi-Producer Multi-Consumer Queue on Ring Buffer | Jun 12, 2013 |
| Weechat, Irssi's Little Brother | Jun 11, 2013 |
| One Tail Just Isn't Enough | Jun 07, 2013 |
| Introduction to MapReduce with Hadoop on Linux | Jun 05, 2013 |
- Containers—Not Virtual Machines—Are the Future Cloud
- Non-Linux FOSS: libnotify, OS X Style
- Linux Systems Administrator
- Validate an E-Mail Address with PHP, the Right Way
- Lock-Free Multi-Producer Multi-Consumer Queue on Ring Buffer
- Senior Perl Developer
- Technical Support Rep
- UX Designer
- Introduction to MapReduce with Hadoop on Linux
- RSS Feeds
- Bought photoshop CS5 for developing a website :(
1 hour 28 min ago - What the author describes
2 hours 54 min ago - Reply to comment | Linux Journal
7 hours 4 min ago - Reply to comment | Linux Journal
7 hours 50 min ago - Didn't read
8 hours 32 sec ago - Reply to comment | Linux Journal
8 hours 5 min ago - Poul-Henning Kamp: welcome to
10 hours 15 min ago - This has already been done
10 hours 16 min ago - Reply to comment | Linux Journal
11 hours 1 min ago - Welcome to 1998
11 hours 50 min ago







Comments
Javascript is still alive
Just goes to show that Javascript is still alive.I wonder how much memory it takes to compile from Coffee Script into Javascript.That might be a limiting factor in development.
The setup was confusing. How
The setup was confusing. How would you set this up for testing in a web browser?
Quite bad code formatting for
Quite bad code formatting for a whitespace-aware language.