Forum Discussion

francisd84's avatar
francisd84
Contributor
3 years ago

Javascript Classes vs. //USEUNIT

I was a little bit surprised when I tried to create an object from a class located in another file within the same project when this file is imported using //USEUNIT and got a reference error     ...
  • francisd84's avatar
    francisd84
    3 years ago

    Thanks Marsha_R

     

    I already read this page and didn't found answers that I wanted.

     

    BUT, I think I found a workaround that will limit the use of "require" in one file only.

     

    So if //USEUNIT only imports global variables and functions, so why not put the "require" statement within it's own file and then use //USEUNIT to import it?

     

    //File A
    
    var AClasses = require("A");
    
    class MyClass
    {
       constructor(x)
       {
          this.x = x;
       }
       GetX()
       {
          return this.x
       }
    }
    
    module.exports.MyClass = MyClass;
    
    
    //File B
    //USEUNIT A
    
    function test()
    {
      var myObj = new AClasses.MyClass(5)
      //Works!
    }

     

    IMO, this is a more cleaner way if we want to use the class in multiple units, we just need to use //USEUNIT instead of declaring another variable in each file.