[英]Node.js + CoffeeScript - modules/class confusion
I understand how to use Protoype in standard Javascript with Node.js and modules, but am having a rough time equating them in CoffeeScript.我了解如何在标准 Javascript 中使用 Protoype 与 Node.js 和模块,但我很难将它们等同于 CoffeeScript。
Let's say I have a file called mymodule.coffee
:假设我有一个名为
mymodule.coffee
的文件:
Module = {}
class MyModule
constructor: (parameter) ->
Module = this
Module.parameter = parameter
standardFunction = (parameter) ->
return parameter
callbackFunction = (parameter, callback) ->
callback parameter
exports.MyModule = MyModule
And I have another file called test.coffee
in the same directory, which I run via coffee test.coffee
, but get an error TypeError: Object #<MyModule> has no method 'standardFunction'
when trying to access the class MyModule
:我在同一目录中有另一个名为
test.coffee
的文件,我通过coffee test.coffee
运行它,但在尝试访问 class MyModule
时收到错误TypeError: Object #<MyModule> has no method 'standardFunction'
:
myModule = require 'mymodule'
myModule = new myModule.MyModule 'parameter'
console.log myModule.standardFunction 'parameter'
myModule.callbackFunction 'parameter', (response) ->
console.log 'Response: ' + response
What am I doing wrong?我究竟做错了什么?
You have mistake in a syntax:你有语法错误:
standardFunction = (parameter) ->
return parameter
should be应该
standardFunction : (parameter) ->
return parameter
( :
instead of =
) The first one is converted to (
:
而不是=
) 第一个转换为
standardFunction = function(parameter) {
return parameter;
}
which gives you nothing (no relation to class), while the second one to这给你什么都没有(与阶级无关),而第二个给
MyModule.prototype.standardFunction = function(parameter) {
return parameter;
}
which is what you want.这就是你想要的。
By the way, you can use CoffeeScript in your constructor like this:顺便说一句,您可以在构造函数中使用 CoffeeScript,如下所示:
constructor: (parameter) ->
@parameter = parameter
Just to be a bit more concise:只是为了更简洁一点:
constructor:(@param)->构造函数:(@param)->
The above code will translate to this.param = param上面的代码会翻译成 this.param = param
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.