【问题标题】:CoffeeScript and NodeJS: How do I export multiple classes?CoffeeScript 和 NodeJS:如何导出多个类?
【发布时间】:2012-06-21 05:42:12
【问题描述】:

我想导出一些类,比如DogCat。解决此问题的一种方法是:

class Dog
  bark: -> console.log "Arff! :D"

class Cat
  meaow: -> console.log "Meaw!"


module.exports = {Dog, Cat}

如何在不输入两次类名的情况下做类似的事情?

【问题讨论】:

  • 如果添加第三个类,是否也要导出?

标签: node.js coffeescript commonjs


【解决方案1】:

你可以这样使用:

class exports.Dog
  bark: -> console.log "Arff! :D"

这编译为:

exports.Dog = (function() {

  function Dog() {}

  Dog.prototype.bark = function() {
    return console.log("Arff! :D");
  };

  return Dog;

})();

【讨论】:

    【解决方案2】:

    另一种方法是执行以下操作:

    module.exports = 
       Dog: class Dog
              bark: -> console.log "Arff! :D"
    
       Cat: class Cat
             meaow: -> console.log "Meaw!"
    

    然后您可以执行以下操作:

    animals = require './animals'
    
    dog = new Animals.dog()
    

    【讨论】:

      【解决方案3】:

      通常我想要一个局部变量(所以我不必一直键入exports.x)和一个导出变量(所以我最后不必一次定义所有导出),所以我执行以下操作:

      exports.dog = class Dog
        bark: ->
      
      exports.cat = class Cat
        meow: ->
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-04-19
        • 1970-01-01
        • 1970-01-01
        • 2018-10-16
        • 1970-01-01
        • 2020-10-22
        • 1970-01-01
        相关资源
        最近更新 更多