Coffeescript和node.js混淆。需要实例化类? [英] Coffeescript and node.js confusion. require instantiates class?
问题描述
我无法尝试让我的类在我的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未定义。这是有道理的,因为它调用的构造函数,但为什么它调用的构造函数即使我没有调用新的麦克风?
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 ?
编辑
修复缩进后
Edit After fixing the indentation
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'
- 使用咖啡
就可以了;与运行编译的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
的构造函数,在类
下面缩进一级,即:
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
是导出的对象。请参阅此处:
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:
-
导出
Mic
作为Mic.coffee的整个导出,而不是键:
Export
Mic
as the entire export of Mic.coffee, and not as a key:
module.exports = Mic
取出整个模块,然后在<:p>
Get the entire module out, and then instantiate the Mic
object within:
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屋!