I'm attempting to write a node module in order to clean up my code and separate it out into different files.
Consider the below code:
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 handler for a specific route, i get an HTTP 500 internal server error.
I've narrowed the problem down to the call to World(), if I change the Hello function to
Hello : function(request, reply) {
return reply("Hello World");
}
Then it works fine, so it seems that it is being tripped up when calling another function from within the export object
Does anyone know why this is happening and how to resolve it?
You should call it as follows:
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 that 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 be exporting what you actually need. This question has other solutions to your issue.
Well let's demonstrate the this
this
doesn't define the object that the function resides in. It defines from where the function is called. So while;
var obj = { Hello : function(request, reply) { return reply("Hello " + this.World()); }, World : function() { return "World"; } }; obj.Hello("test", console.log);
would work just fine; This wouldn't;
var obj = { Hello : function(request, reply) { return reply("Hello " + this.World()); }, World : function() { return "World"; } }; setTimeout(obj.Hello,100,"test",console.log);
This is just because the obj.Hello
will be assigned an argument in setTimeOut
function's definition and that argument will be invoked as window
being the this
for that function. So you should instead do like;
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);
You'll need to add this
to your invocation of World()
-
module.exports = {
Hello : function(request, reply) {
return reply("Hello " + this.World());
},
World : function() {
return "World";
}
}
World
is an attribute of the export object, not a variable within the accessible scope - so you need to specify that the function belongs to this
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.