Jump to content

[Javascript] How can I share variables between JS files?

G1K777

Is there any way to share variables between js files?
I have one JS file with classes and one js file with a frontend "template".

 

frontend.js
 

  // Create Objects
  const
  header = new Nav("header"),
  nav = new Nav("nav"),
  main = new Element("main"),
  aside = new Element("aside"),
  footer = new Nav("footer");

  // Add nodes to the body element.
  header.init(document.body);
  nav.init(document.body);
  main.init(document.body);
  aside.init(document.body);
  footer.init(document.body);

  // Set objects inner html?
  header.set([["/loginsystem/index.php","Login"],["/loginsystem/index.php","Signup"]]);
  nav.set([["#","Home"],["#","Community"]]);
  footer.add(["https://github.com/damiantoczek/frontend", "Github"]);

Now I want to create another html file lets say, signup.html and add a signup.js file and this file should be able to access the created class instances.

signup.js
 

// Testing form
const signupForm = new Form("signup");
signupForm.init(main.node);
signupForm.add([ ["username"], ["password"], ["email"] ]);

 

AMD FX8320 | GTX660 | 4x4GB DDR3 | LG ZR2740W

Logitech Wireless Pro  | Logitech G413 | Nuforce uDAC5  | AKG K612

Link to comment
Share on other sites

Link to post
Share on other sites

If they're global variables then they can be accessed by any file

 

Although, this isn't really a good way of doing things. I suggest using something like webpack and split the code into modules which can be imported and executed in the main file

🙂

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, duncannah said:

If they're global variables then they can be accessed by any file

Yeah, I can imagine that but how do I set global variables?

AMD FX8320 | GTX660 | 4x4GB DDR3 | LG ZR2740W

Logitech Wireless Pro  | Logitech G413 | Nuforce uDAC5  | AKG K612

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, G1K777 said:

Yeah, I can imagine that but how do I set global variables?

EIther set them in the global scope, or set it in the window object.

 

Again, I suggest using modules instead

🙂

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, duncannah said:

EIther set them in the global scope, or set it in the window object.

 

Again, I suggest using modules instead

Found it, it lost scope because of "window.onload".

AMD FX8320 | GTX660 | 4x4GB DDR3 | LG ZR2740W

Logitech Wireless Pro  | Logitech G413 | Nuforce uDAC5  | AKG K612

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×