Coffeescript and confusion node.js. instance class required?

I am having trouble trying to get my class to work in my node.js file. When I need the module I wrote, require './module' calls my constructor and gives an error. But I really want to create an instance later in the file.

i.e

class Mic constructor: (x) -> @t = [] @t.push x exports.Mic = Mic 

and here is my app.coffee file

 require 'coffee-script' require './Mic' 

When I run app.coffee, it throws a ReferenceError: x exception undefined. What makes sense from the moment the constructor is called, but why does it invoke the constructor, although I did not name the new Mic?

Edit After Indenting

 class Mic constructor: (x) -> @t = [] @t.push x exports.Mic = Mic 

and update my app.coffee to

 Mic = require './Mic' m = new Mic 3 console.log m 

I get an error

 TypeError: object is not a function at Object.CALL_NON_FUNCTION_AS_CONSTRUCTOR (native) 
+6
source share
1 answer

The first thing you need: you do not need require 'coffee-script' - perhaps it is with coffee ; similar to running compiled JavaScript. You do not need the CoffeeScript library available at runtime of your program.

Secondly, the first file has the wrong indent; if you want this to be a Mic constructor, backtrack it one level below the class , i.e.:

 class Mic constructor: (x) -> @t = [] @t.push x exports.Mic = Mic 

Finally, the problem is that exports is an export object . See here:

 exports.Mic = Mic 

You assigned Mic to the exports Mic object, so now exports in Mic.coffee looks like this:

 { Mic: ...your class... } 

When you say require './Mic' , you return this object; in other words:

 require('./Mic') == { Mic: ...your class... } 

So you need to do one of the following:

  • Export Mic as all Mic.coffee exports, not as a key:

     module.exports = Mic 
  • Extract the entire module, and then instantiate the Mic object inside:

     mic = require './Mic' m = new mic.Mic 3 
  • Take Mic out of the require module:

     {Mic} = require './Mic' # equivalent to saying Mic = require('./Mic').Mic m = new Mic 3 
+17
source

Source: https://habr.com/ru/post/916773/


All Articles