0

I am a little confused regarding varable scope. The below code does not execute the playerDetails function properly - UNLESS I declare the variable 'panel' inside the function block.

However - I thought if a variable was declared outside of a function block it therefore has global scope - and is visible to all function blocks.

In short - I can get the code to work by moving the first line into the playerDetails function block - I just don't see why I should need to do that. Any help would be much appreciated.

Thanks. Code below ;

var panel = document.getElementById ( "panel" ) ;

function init()
{
var player1 = {name: "DJCraigo" , score: 178242 , rank: "1st"} ;
var player2 = {name: "Tohny" , score: 155522 , rank: "2nd"} ;
player1.showDetails = playerDetails ;
player2.showDetails = playerDetails ;

player2.showDetails() ;

player1.showDetails() ;
}

function playerDetails()
{
  panel.innerHTML += "Player with name " + this.name + " is ranked " + this.rank + " with a         score of " + this.score + "<br>" ;
}
document.addEventListener ( "DOMContentLoaded" , init , false ) ; 
DJC
  • 1,175
  • 1
  • 15
  • 39

1 Answers1

1

The line with the declaration / initialization of panel variable gets executed just when it is read. And the DOM is probably not initialized, so, getElementById does not return anything.

If you want your variable to be global, declare it as you are doing, but initialize (getElementById) inside the init function.

var panel;
function init()
{
    panel = document.getElementById ( "panel" ) ;
...
MC ND
  • 69,615
  • 8
  • 84
  • 126