Make a simple private variable global - accessing body elements

时间:2019-01-09 21:41:30

标签: javascript

A beginner question indeed but can't find anywhere on stackoverflow that actually solves this, so any help would be really appreciated. I just want to define a private variable and then return it to the global scope.

In this example, I can access x in the JS console after refreshing the page - but the script runs before the body loads (source at end of head tag) and I cannot create elements that relate to the body content since they haven't loaded yet:

var x = 5;

window.onload = function() {
    var y = 10;
}

I cannot access variable y, presumably because it's a private variable that's not available on the global scope (am I actually correct here?). Using return fails. I just want to be able to create variables from the body, but I can't because the script hasn't loaded in time.

How can this be achieved? I actually can't solve this presumably simple problem. Thanks for any help here.

4 个答案:

答案 0 :(得分:2)

A simple way that I use when I need a variable in my console, is assigning them to window like this:

window.y = y;

Then in your console, y as well as window.y will be that variable :)

答案 1 :(得分:2)

Declare y in the global scope and initialize it in the onload function.

var x = 5;
var y;
window.onload = function() {
    y = 10;
}

答案 2 :(得分:1)

You could create a global namespace and add properties later to it.

var namespace = Object.create(null); // empty object without prototypes

window.onload = function() {
    namespace.y = 10;
}

答案 3 :(得分:1)

You obviously can't access y outside of a window.onload function like this, since the window hasn't loaded by the time you check what y is.

var x = 5;

window.onload = function() {
    var y = 10;
}

console.log(y)

Assuming you don't mean that and you're just using onload as an example of a function, you can use window.y as a substitute for var y and it will be global on the window, so you can use it outside of the function.

var x = 5;

function define_y() {
  window.y = 10;
}

window.onload = function() {
  define_y();
  console.log(y);
}