CoffeeScript: How to instantiate a class with an attributes hash

Posted Over 9 years ago. Visible to the public.

This may be hard to find in the docs, but if you want CoffeeScript classes that instantiate their properties from a hash of attributes (like ActiveRecord), do it like this:

class User
  constructor: ({ @name, @email }) ->
    # empty contstructor is fine, CoffeeScript will do the magic.

Example:

var batman = new User(name: 'Bruce Wayne', email: 'batman@example.com')
batman.name # => 'Bruce Wayne'
Arne Hartherz
Last edit
Over 9 years ago
Deleted user #20
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2014-10-22 09:53)