Calling a function of a Node.js module from a module

I am trying to write a node module to clear my code and split it into different files.

Consider the code below:

module.exports = { Hello : function(request, reply) { return reply("Hello " + World()); }, World : function() { return "World"; } } 

If I import the above module and use the Hello function as a handler for a specific route, I get an internal HTTP 500 server error.

I narrowed down the problem to calling World () if I changed the Hello function to

 Hello : function(request, reply) { return reply("Hello World"); } 

Then it works fine, so it seems to work when another function is called from the export object

Does anyone know why this is happening and how to solve it?

+5
source share
3 answers

You should call it like this:

 module.exports = { Hello: function(request, reply) { return reply("Hello " + module.exports.World()); }, World: function() { return "World"; } } 

If you are aiming for cleaner code, I suggest you change the code to this:

 function World() { return "World"; } function Hello(request, reply) { return reply("Hello " + World()); } module.exports = { Hello, } 

This will make your code more readable and you will only export what you really need. This question has other solutions to your problem.

+4
source

Well demonstrate this

this does not determine the object this function is in. It determines which function is called. So for now;

 var obj = { Hello : function(request, reply) { return reply("Hello " + this.World()); }, World : function() { return "World"; } }; obj.Hello("test", console.log); 

will work fine; It will not be;

 var obj = { Hello : function(request, reply) { return reply("Hello " + this.World()); }, World : function() { return "World"; } }; setTimeout(obj.Hello,100,"test",console.log); 

This only happens because obj.Hello will be assigned an argument in the definition of the setTimeOut function, and this argument will be called as window , which is this for this function. So you should do like this:

 var obj = { Hello : function(request, reply) { return reply("Hello " + this.World()); }, World : function() { return "World"; } }; setTimeout(obj.Hello.bind(obj),100,"test",console.log); //or setTimeout(obj.Hello.bind(obj,"test",console.log),100); //or setTimeout((x,y) => obj.Hello(x,y),100,"test",console.log); 
+3
source

You need to add this to your World() call -

 module.exports = { Hello : function(request, reply) { return reply("Hello " + this.World()); }, World : function() { return "World"; } } 

World is an attribute of an export object, not a variable in an accessible area - so you need to indicate that the function belongs to this .

+2
source

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


All Articles