简体   繁体   中英

how to initiate a class from variable CoffeScript

How would one initiate a class from a variable in CoffeScript? in another words:

className = 'Domain'
domain = new className()

should.exist(domain)
'Domain'.should.equal(domain.constructor.name)

How would the line two should look like to satisfy the assertions? Thank You

Edit: The class is declared as following

class Domain
  constructor: (obj) ->
    for own key, value of obj
      @[key] = value

  save: (fn) ->
    self = @
 ...
module.exports = Domain

Peter Lyons answer works with a little adjustments to the way our class defined. In short, the solution:

DomainClass = require('./index')
newDomain = new DomainClass({...})

You just need to lookup the class name using square brackets in the correct scope. In a browser, you could do new window[className] or in node if your class was in a module you could do new require('./models')[className] .

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