mahemoff
mahemoff

Reputation: 46489

Initialising a CoffeeScript class instance from a hash

I thought this might be built-in, but doesn't seem to be. What's the best way to do populate a new class instance from a hash of properties?

Upvotes: 2

Views: 369

Answers (2)

david
david

Reputation: 18288

It is indeed built in. You can put @ symbols infront of the variables inside the hash:

class Cat
  constructor: ({@name, @age}) ->


myCat = new Cat {name:'kitty', age:3}

This is part of "Destructuring Assignment" which you can read about on the coffescript website. It even works with nested objects, arrays and even splats.

Upvotes: 6

Jimmy
Jimmy

Reputation: 37091

You could do something like this:

class Foo
  constructor: (params = {}) ->
    for key, value of params
      this[key] = value

f = new Foo(var1: "foo", var2: "bar")
console.log(f)

Upvotes: 1

Related Questions