javascript - Node.js + CoffeeScript - 模块/类混淆

标签 javascript node.js coffeescript

我了解如何在标准 Javascript 中使用 Protoype 与 Node.js 和模块,但在 CoffeeScript 中将它们等同起来却很困难。

假设我有一个名为 mymodule.coffee 的文件:

Module = {}

class MyModule

  constructor: (parameter) ->

    Module = this
    Module.parameter = parameter

  standardFunction = (parameter) ->

    return parameter

  callbackFunction = (parameter, callback) ->

    callback parameter

exports.MyModule = MyModule

我还有另一个名为 test.coffee 的文件在同一目录中,我通过 coffee test.coffee 运行该目录,但出现错误 TypeError: Object #<MyModule> has no method 'standardFunction'当尝试访问类 MyModule 时:

myModule = require 'mymodule'
myModule = new myModule.MyModule 'parameter'

console.log myModule.standardFunction 'parameter'

myModule.callbackFunction 'parameter', (response) ->

  console.log 'Response: ' + response 

我做错了什么?

最佳答案

您的语法有错误:

standardFunction = (parameter) ->
    return parameter

应该是

standardFunction : (parameter) ->
    return parameter

(: 而不是 =) 第一个被转换为

standardFunction = function(parameter) {
    return parameter;
}

它没有给你任何东西(与类无关),而第二个给你

MyModule.prototype.standardFunction = function(parameter) {
    return parameter;
}

这就是你想要的。

顺便说一句,您可以在构造函数中使用 CoffeeScript,如下所示:

constructor: (parameter) ->
    @parameter = parameter

关于javascript - Node.js + CoffeeScript - 模块/类混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10062135/

相关文章:

javascript - NodeJs 在执行测试用例时用 Jest 错误表达 MongoDB

javascript - rails 5.1 : How to override confirmation dialog with bootstrap using rails-ujs

javascript - 在 cson 文件中的三重引号内插入三重引号

javascript - Angular - 在 localStorage 中存储和读取带有状态的复选框列表

javascript - HTML5 可拖动列表 - 多个 setData?

javascript - Rails 浏览器语法高亮插件?

node.js - Jade 中元素的动态宽度

javascript - TypeError : By. cssSelector 不是函数

javascript - 如何在 Rails 4 中通过 Turbolinks 使用页面/查看特定的 Javascript?

javascript - ES6中如何检查类是否覆盖父方法