Reputation: 965
I'm trying to figure out how inheritance works in coffeescript. Here's a simplified example of my code:
class Parent
constructor: (attrs) ->
for own name,value of attrs
this[name] = value
Parent.from_json_array = (json, callback) ->
for item in JSON.parse(json)
obj = new ChildA item # [1]
callback obj
class ChildA extends Parent
class ChildB extends Parent
ChildA.from_json_array("[{foo: 1}, {foo: 2}]") (obj) ->
console.log obj.foo
What do I need to put on the line marked [1]
to use the correct child class here? This works, but only creates objects with a prototype of ChildA
. I've tried something like:
Parent.from_json_array = (json, callback) ->
klass = this.prototype
for item in JSON.parse(json)
obj = klass.constructor item # [1]
callback obj
... but this leaves obj
as undefined in my callback function (TypeError: Cannot read property 'foo' of undefined".
Whats the magic incantation in CoffeeScript to be able to create a new object of a class, where the class is variable?
Upvotes: 2
Views: 2382
Reputation: 965
Nevermind, I figured it out:
Parent.from_json_array = (json, callback) ->
klass = this
for item in JSON.parse(json)
obj = new klass item
callback obj
Turns out you can just new
a class stored in a variable. I thought I had tried this before, but was getting a syntax error.
Upvotes: 2