Window.onload without a global variable

I am trying to use windows.load without a global variable.

HTML code:

<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>Test</title> <link rel="stylesheet" href="main.css"> <script type="text/javascript" src="script.js"></script> </head> <body> <form> Name: <input type="text" id="txt1"><br><br> <input type="button" value="Check Input" id="b1"> </form> </body> </html> 

JavaScript global variable code:

 /*jslint browser: true*/ var myButton; window.onload = function () { "use strict"; myButton = document.getElementById("b1"); myButton.addEventListener("click",alertMM); }; function alertMM() { "use strict"; window.console.log(myButton.value); } 

And finally, NOT WORKING without the global variable code:

 /*jslint browser: true*/ var myNS = { myButton: undefined, // setUp: function () { "use strict"; myNS.myButton = document.getElementById("b1"); myNS.myButton.addEventListener("click", alertMM); } }; window.onload = myNS.setUp(); function alertMM() { "use strict"; window.console.log(myNS.myButton.value); } 

The reason I want to stop using the global variable is because I'm afraid that it will conflict with future code.

Thank you in advance

Adrian

+6
source share
2 answers

IN:

 window.onload = myNS.setUp(); 

when you define the window.onload callback, you must assign the function itself (just myNS.setUp ) so that it can be called later. What your code does instead calls the function immediately and assigns the result.

+5
source

The variable scope in JavaScript is mainly focused on scope. As in, functions enclose their internal variables. That way, you can avoid contaminating the global scope simply by declaring your variables (and assigning DOM el) to the function you are assigning window.onload :

 window.onload = function() { //variable assignments inside the function var button1 = document.getElementById('b1'); var button2 = document.getElementById('globalCheck'); //anonymous functions attached instead of named functions button1.addEventListener('click', function() { alert(button1.value); }); button2.addEventListener('click', function() { alert("var button1 in the global scope: " + window.button1 + "\n" + "var button2 in the global scope: " + window.button2); }); }; 
 .greyButton { background-color: grey; color: #f5f5f5; width: 30%; } #txt1 { width: 29%; } 
 <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>Test</title> <link rel="stylesheet" href="main.css"> <script type="text/javascript" src="script.js"></script> </head> <body> <form> <div> <input type="text" id="txt1" placeholder="Name" value=""> <br> <input type="button" value="Check Input" id="b1" class="greyButton"> </div> <br> <div> <input type="button" value="Are the variables global?" id="globalCheck" class="greyButton"> </div> </form> </body> </html> 
0
source

Source: https://habr.com/ru/post/985420/


All Articles