I understand how to use Protoype in standard Javascript with Node.js and modules, but am having a rough time equating them in CoffeeScript.
Let's say I have a file called 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
:
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:
constructor: (parameter) ->
@parameter = parameter
Just to be a bit more concise:
constructor:(@param)->
The above code will translate to this.param = param