我遇到了node.js的另一个问题,这次我无法获取我的javascript代码来识别coffeescript模块的类有功能。
在我的主文件main.js中,我有以下代码:
require('./node_modules/coffee-script/lib/coffee-script/coffee-script');
var Utils = require('./test');
console.log(typeof Utils);
console.log(Utils);
console.log(typeof Utils.myFunction);
在我的模块test.coffe中,我有以下代码:
class MyModule
myFunction : () ->
console.log("debugging hello world!")
module.exports = MyModule
这是我运行node main.js
时的输出:
function
[Function: MyModule]
undefined
我的问题是,为什么我的主文件加载了正确的模块,但为什么它无法访问该函数?我做错了什么,无论是使用coffeescript语法,还是我需要我的模块?如果我应该澄清我的问题,请告诉我。
谢谢,
维尼特
答案 0 :(得分:6)
myFunction
是实例方法,因此无法直接从class
访问。
如果您希望将其作为类(或静态)方法,请在名称前添加@
以引用该类:
class MyModule
@myFunction : () ->
# ...
如果所有方法都是 static ,您也可以导出Object
:
module.exports =
myFunction: () ->
# ...
否则,您需要在main
:
var utils = new Utils();
console.log(typeof utils.myFunction);
或者,作为导出对象:
module.exports = new Utils