0

Hoping somebody could please explain this to me- why can I call the second function from the first without error in the first 2 examples, but the third example errors out.

I can write a module like so:

function main () {
   const double = doubleThis(5)
   console.log(double);
}

function doubleThis(num) {
   let answer = num*2;
   return answer;
}

or like this:

module.exports = {
   run: function(){
      const double = doubleThis(5);
      console.log(double);
   }
}

function doubleThis(num){
   let answer = num*2
   return answer;
}

However, something like this is not allowed:

module.exports = {
   run: function(){
      const double = doubleThis(5);
      console.log(double);
   }, 
   
   doubleThis: function(num){
      let answer = num*2;
      return answer;
   }
}
boog
  • 472
  • 1
  • 5
  • 23
  • 2
    1. Hoisting. 2. Inside an object's method, you cannot refer to functions by name and you have to use `this` – VLAZ Feb 07 '22 at 17:35
  • 1
    because `doubleThis` wouldn't be a function to it – The Bomb Squad Feb 07 '22 at 17:35
  • @VLAZ I don't see how this is related to hoisting. – Bergi Feb 07 '22 at 18:00
  • Btw, `answer = num*2;` is missing a declaration and should throw an exception in a strict mode module. – Bergi Feb 07 '22 at 18:01
  • @Bergi the question is not entirely clear. OP is asking "how does it work". Without any guidance for *what* works or why they were asking. I've listed all the relevant things - in the first one hoisting may be involved. Again, really hard to judge based on the question. Now *with an answer*, it seems it was just "how do I call a method on an object" rather than "explain how this code works" but I could not really guess that's what OP really meant. – VLAZ Feb 07 '22 at 18:06
  • fixed the missing declaration - the purpose of the question was basically, why does calling the method work in the first two examples but not the third, where both methods are contained within the module.exports object. What I gather is that you need to use `this` when calling methods from within the same object? – boog Feb 07 '22 at 18:17

1 Answers1

0

Thanks, this.doubleThis(5) works fine- embarrassing question but maybe somebody else might wonder same thing. I'm familiar with usage of this in prototypes but apparently not familiar enough with how this applies everywhere else... will review hoisting. Thanks again.

boog
  • 472
  • 1
  • 5
  • 23
  • 1
    I'd recommend taking a look through [this answer](https://stackoverflow.com/a/3127440/4987197) to better understand the `this` keyword – mhodges Feb 07 '22 at 17:43