node.js coffeescript - 需要模块的问题

Vin*_*aju 4 node.js coffeescript

我对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);
Run Code Online (Sandbox Code Playgroud)

在我的模块test.coffe中,我有以下代码:

class MyModule

  myFunction : () ->
    console.log("debugging hello world!")

module.exports = MyModule
Run Code Online (Sandbox Code Playgroud)

这是我运行时的输出node main.js:

function
[Function: MyModule]
undefined
Run Code Online (Sandbox Code Playgroud)

我的问题是,为什么我的主文件加载了正确的模块,但为什么它无法访问该函数?我做错了什么,无论是使用coffeescript语法,还是我需要我的模块?如果我应该澄清我的问题,请告诉我.

谢谢,

维尼特

Jon*_*ski 6

myFunction是一个实例方法,所以它不能直接从class.

如果您希望它作为(或静态)方法,请在名称前加上@以引用该类:

class MyModule

  @myFunction : () ->
    # ...
Run Code Online (Sandbox Code Playgroud)

Object如果所有方法都是静态的,您也可以导出:

module.exports =

  myFunction: () ->
    # ...
Run Code Online (Sandbox Code Playgroud)

否则,您需要在以下位置创建实例main:

var utils = new Utils();
console.log(typeof utils.myFunction);
Run Code Online (Sandbox Code Playgroud)

或者,作为导出对象:

module.exports = new Utils
Run Code Online (Sandbox Code Playgroud)