Calling a second function from a function.
-
Let me start of by saying that before playing screeps i never wrote a single line of code in Javascript - i can write basic code in several other languages but i am quite a novice at most of those. Most issues i run into i can google my way out of but with one issue i seem to have run into a wall.
What i effectively want to do is call a second function from a main function. The below two scripts are a simplified example of what i am trying to achieve:
-- main.js --
var trial = require('trial');
module.exports.loop = function () {
trial.outer();
}
-- trial.js --
module.exports =
{
outer: function()
{
inner('ValueToPassOn')
},
inner: function(value)
{
console.log(value)
}
}
What i hoped to achieve was calling trial.outer() in the main function, with the result being that it would call "inner()" and write some test data to the console. In the actual function the "outer" function has to do a variable number of calls to "inner" with different parameters.
I can think of multiple ways to work around the issue itself; I could create a new "trial.sub.js" which would contain the inner function and just include it in the current file for example. That, and all of the other ideas sound like bad coding practice in my mind.
What am i missing here? Is there any way to call a function in trial.js using a function in trial.js? Thanks in advance for the assist here!
-
I think the problem is inner is not in the scope where you call it. If you change the above exaple to module.exports.inner('value') it should work.
Normally, you would use a class pattern and call this.inner, or define the inner function outside module.exports, so that it is in scope of the function inside.
-
"this" is actually the way to do it. i was stumped with this for some time, too, but if you do the call with this.inner('ValueToPassOn'); it should work.
-
Thank you both for the valuable hints!
The "class pattern" comment made me realize that a function within a function actually works like a class, and after realizing that several googled code snippets started making sense. The mention of "this." being able to access objects within that class solved the rest of the puzzle for me.
If someone would happen to stumble upon this question: The code below is a rewritten version of my simplified code above, this time in working order.-- main.js --
var Logdata = require('trial')('This is the input data');module.exports.loop = function () {
Logdata.logvalue()
}-- trial.js --
var classStructure = function(input){
return {
savedinput: input,logvalue: function()
{
console.log(this.savedinput)
}
};
};module.exports = classStructure
It is also possible to add new function in the "Return" statement within trial.js. That function could then call this.logvalue to invoke the logvalue function.