N
N
Nwton2016-07-10 16:54:08
Node.js
Nwton, 2016-07-10 16:54:08

Why is it impossible to get and give module.exports in one file?

There is a module to which, when connected, a function / variable is passed, for example, like this:
myModule = require('./mymodule')(param);
In the module, the variable is received like this:

var param;
module.exports = function(item){
  param = item;
}

And it works, now the param from the external file is available in myModule.
But at the same time, it is impossible to transfer anything from myModule. If I do this in myModule:
echo = function(){
  console.log('ok');
}
module.exports.echo = echo;

And in an external file like this:
myModule.echo();
That will give an error "Cannot read property 'echo' of undefined".
What can be done?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Yarkov, 2016-07-10
@Nwton

mymodule.js

var param = "param";

module.exports = function(item){
    var self = this;
    param = item;
    self.echo = function(){
        console.log(param);
    }
    return {
        echo: self.echo
    }
}

var myModule = require('./mymodule')("newparam");
myModule.echo();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question