简体   繁体   中英

Coffeescript: dynamically create instance of the class a method is called on

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.

@find: (id, cb,klass=RedisObject) ->
    client.HGETALL "#{@className()}|#{id}", (err, obj) =>
      unless err
        cb(new klass(obj, false))

and in the sub class

@find: (id, cb,klass=User) ->
    super(id,cd,klass)

that's what i would do though it is not 100% dynamic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM