I am building a Node.js application using object oriented coffeescript.
I have a super class
with a static method like:
class RedisObject
@find: (id, cb) ->
client.HGETALL "#{@className()}|#{id}", (err, obj) =>
unless err
cb(new RedisObject(obj, false))
There is a subclass like
class User extends RedisObject
When I call find()
on the User class
I want it to pass a instance of User
instead of RedisObject
to the callback function.
I tried to realize this by getting the class name of the actual class the method is called on by using
@constructor.name
and use eval()
to generate an instance from it - but the problem is that the subclass will be undefined from within the superclass.
How can I realize the behaviour of getting different types of instances returned by the find
method depending on which class it is called on, without having to override it in each subclass?
I'm not an expert in CoffeeScript, but wouldn't this work?
class RedisObject
whoami: () -> "I am a RedisObject"
@find: () ->
new this()
class User extends RedisObject
whoami: () -> "I am a User"
console.log RedisObject.find().whoami() // -> "I am a RedisObject"
console.log User.find().whoami() // -> "I am a User"
At least the above test seems to pass.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With