最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - window.onload without global variable - Stack Overflow

programmeradmin0浏览0评论

I'm trying to use windows.load without global variable.

The 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>

I'm trying to use windows.load without global variable.

The 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>

The 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 the NOT WORKING without 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 that I want to stop using global variable is that I'm afraid it will conflict with future code.

Thanks in advance

Adrian

Share Improve this question asked Apr 18, 2015 at 13:10 Adrian GherasimAdrian Gherasim 1351 gold badge4 silver badges10 bronze badges 5
  • BTW, you could use this.myButton = as an alternative to myNS.myButton =. Probably a matter of personal preference in this case... – Matt Browne Commented Apr 18, 2015 at 13:22
  • you can use the IIFE pattern and wrap eveyrthing in a self executing function, which sets an inner scope and won't let variables leak to the global scope – yoavmatchulsky Commented Apr 18, 2015 at 13:27
  • or you can define alertMM() inside your onload function and use the same myButton object – yoavmatchulsky Commented Apr 18, 2015 at 13:28
  • Actually you should clearup this code. If you are using addEventListener, use it everywhere, don't need to fallback to window.onload thing. Improve your namespace with module pattern. It will make your code more strict and easer to understand. When you need to assign method - use the closures `window.onload=function(){..}' – Nagh Commented Apr 18, 2015 at 13:39
  • What do you mean, "use it everywhere, don't need to fallback to window.onload thing", can you give me an example? – Adrian Gherasim Commented Apr 18, 2015 at 13:50
Add a ment  | 

2 Answers 2

Reset to default 5

In:

window.onload = myNS.setUp();

when you define the window.onload callback, you should assign it the function itself (just myNS.setUp) so it can be called later. What your code doing instead is calling the function immediately and assigning the result.

Variable scoping in JavaScript is primarily function scope oriented. As in, functions enclose their inner variables. So you could avoid polluting the global scope simply by declaring your variables (and assigning the DOM el) within the function that you're assigning to 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)

  1. 暂无评论