【问题标题】:Node.js module.exports in CoffeeScriptCoffeeScript 中的 Node.js module.exports
【发布时间】:2012-08-31 20:42:45
【问题描述】:

我正在研究一个简单的例子;我可以让它与 Javascript 一起工作,但我的 CoffeeScript 版本有问题。

这是person.coffee:

module.exports = Person

class Person 
    constructor: (@name) ->

    talk: ->
        console.log "My name is #{@name}"

这里是 index.coffee:

Person = require "./person"
emma = new Person "Emma"
emma.talk()

我希望运行 index.coffee 并看到控制台输出“我的名字是 Emma”。相反,我收到一条错误提示 TypeError: undefined in not a function。

【问题讨论】:

    标签: node.js coffeescript


    【解决方案1】:

    将module.exports 放在底部。

    ----person.coffee----

    class Person 
        constructor: (@name) ->
    
        talk: ->
            console.log "My name is #{@name}"
    
    module.exports = Person
    

    Person = require "./person" // [Function: Person]
    p = new Person "Emma" // { name: 'Emma' }
    

    当您分配给顶部的module.exports 时,Person 变量仍然是undefined。

    【讨论】:

    • 仅供参考:了解为什么在 javascript 中查看传统模式来制作模块会很有用
    【解决方案2】:

    你也可以写person.coffee:

    class @Person
    

    然后在index.coffee中使用以下内容:

    {Person} = require './person'
    

    【讨论】:

    • 试过这个并不断收到object is not a function错误。
    • @majidarif 看看你编译的代码,看看它是否有意义。您是在 Node.js 环境还是浏览器中运行?
    • 我实际上在 Node.js 上,我在 1 个文件上有 2 个类,还有 2 个类扩展了这些类中的一个和一个。然后 subcass 就是我需要导出的那个。
    【解决方案3】:

    你也可以写

    module.exports = class Person
      constructor: (@name) ->
        console.log "#{@name} is a person"   
    

    然后在index.coffee 要么

    bob = new require './person' 'Bob'
    

    或者你可以这样做

    Person = require './person'
    bob = new Person 'bob'
    

    【讨论】:

      【解决方案4】:

      这里的各种答案似乎理所当然地认为模块导出的唯一一个对象是类(一种“Java 思维方式”)

      如果你需要导出多个对象(类、函数等),最好这样写:

      exports.Person = class Person
          [...]
      


      coffee> { Person } = require "./person"
      coffee> p = new Person "Emma"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-31
        • 2015-08-19
        • 2015-10-08
        • 1970-01-01
        • 2017-03-10
        • 1970-01-01
        相关资源
        最近更新 更多