Coffeescript 和 node.js 混淆.需要实例化类? [英] Coffeescript and node.js confusion. require instantiates class?

查看:18
本文介绍了Coffeescript 和 node.js 混淆.需要实例化类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试让我的类在我的 node.js 文件中工作时遇到问题.当我需要我编写的模块时,require './module' 调用我的构造函数并给出错误.但我实际上想稍后在文件中实例化.

I'm having trouble trying to get my class working in my node.js file. When I require the module I wrote, the require './module' calls my constructor and gives an error. But I actually want to instantiate later on in the file.

class Mic

constructor: (x) ->
  @t = []
  @t.push x

exports.Mic = Mic

这是我的 app.coffee 文件

and here is my app.coffee file

require 'coffee-script'
require './Mic'

当我运行 app.coffee 时,它​​会给出异常 ReferenceError: x is not defined.这是有道理的,因为它调用了构造函数,但是为什么即使我没有调用 new Mic 也调用构造函数?

When I run app.coffee it gives an exception ReferenceError: x is not defined. Which makes sense since its calling the constructor, but why is it calling the constructor even though I havent called new Mic ?

编辑固定缩进后

class Mic
    constructor: (x) ->
        @t = []
        @t.push x

exports.Mic = Mic

并将我的 app.coffee 更新为

and updating my app.coffee to

Mic = require './Mic'

m = new Mic 3
console.log m

我得到了错误

TypeError: object is not a function
    at Object.CALL_NON_FUNCTION_AS_CONSTRUCTOR (native)

推荐答案

第一件事:你不需要 require 'coffee-script'——用 coffee 运行它代码>就足够了;与运行已编译的 JavaScript 相同.您不需要程序运行时可用的 CoffeeScript 库.

First thing's first: you don't need the require 'coffee-script'—running it with coffee is enough; same as running the compiled JavaScript. You don't need the CoffeeScript library available at runtime in your program.

其次,第一个文件出现缩进错误;如果你想让它成为 Mic 的构造函数,在 class 下缩进一层,即:

Secondly, the first file appears indented incorrectly; if you want that to be Mic's constructor, indent it one level underneath the class, i.e.:

class Mic
  constructor: (x) ->
    @t = []
    @t.push x

exports.Mic = Mic

最后,问题在于 exports 是导出的 object.见这里:

Finally, the issue is that exports is an object of exports. See here:

exports.Mic = Mic

您已将 Mic 分配给 exports 对象的 Mic 键,所以现在在 Mic.coffee 中 exports看起来像这样:

You've assigned Mic to the exports object's Mic key, so now exports in Mic.coffee looks like this:

{ Mic: ...your class... }

当您说 require './Mic' 时,您将获得该对象;换句话说:

When you say require './Mic', you're getting that object back; in other words:

require('./Mic') == { Mic: ...your class... }

因此您需要执行以下操作之一:

So you need to do one of the following:

  1. Mic 导出为 Mic.coffee 的整个导出,而不是键:

  1. Export Mic as the entire export of Mic.coffee, and not as a key:

module.exports = Mic

  • 把整个模块拿出来,然后在里面实例化Mic对象:

    mic = require './Mic'
    m = new mic.Mic 3
    

  • 只需从 require 的模块中取出 Mic:

    {Mic} = require './Mic'  # equivalent to saying Mic = require('./Mic').Mic
    m = new Mic 3
    

  • 这篇关于Coffeescript 和 node.js 混淆.需要实例化类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆