Forum Discussion

royd's avatar
royd
Regular Contributor
7 years ago

Global variable troubles (Calling Variables Declared in Another Unit) in javascript

I have successfully used "//USEUNIT" method of calling functions and variables in the past.  I am trying to use "module.exports" method and can not figure out how  to make it work. Here is what I hav...
  • cunderw's avatar
    cunderw
    7 years ago

    Ah, I forgot the Javascript scope can be a little weird. You won't actually be able to reference that var directly without it being a const. 

     

    So you could approach it two different ways:

     

    let fooString = ""
    
    function setFooString(){
     
     fooString = "Test";
     
    }
    
    function getFooString() {
      
      return fooString;
    }
    
    module.exports.setFooString = setFooString;
    module.exports.getFooString = getFooString;
    // bar file
    
    let foo = require("foo");
    
    function barFunction() { 
      foo.setFooString();
      ShowMessage(foo.getFooString());
    }

    Or you could do a const object like this:

     

    // foo file
    const info = {
      fooString : ""
    }
    
    function setFooString(){
     
     info.fooString = "Test";
     
    }
    
    module.exports.setFooString = setFooString;
    module.exports.info = info;
    // bar file
    
    let foo = require("foo");
    
    function barFunction() { 
      foo.setFooString();
      ShowMessage(foo.info.fooString);
    }

    I personally would prefer the second way because it's much easier to expand on what you're acceessing from the first unit.