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 ) ;