Javascript scoping - creep creep crept

You may already know this, but it’s something that I once knew then forgot: Javascript variable scoping sucks:
  • Variables are automatically global, unless you declare them with the “var” keyword
  • If you create a variable WITHIN a function, it has scope everywhere, including inside other functions
function foo()
{ 
  var x =1; // invisible outside function
  y = 2; // NOT declared.  visible, 
         //and can be modified outside this function 
         //AND INSIDE ANY OTHER FUNCTION
}
This is especially important when you are trying to pass variables into callback functions. To pass a variable to a callback, you have to define the function precisely at the callback:
function getSomeHtml()
{
param_one = “shizzangiggles”;
param_two = 3.14159;

function myCallbackFunction(xr, a, b)
{
    … your code
}

ajax.makeRequest( 
   ‘getHtml’, 
    function( response)
    { 
       myCallbackFunction(response,param_one,param_two); 
    } 
);

Be careful when you do this. If you declare param_one and param_two above ( “var param_one”), your callback will error out, because these two variables are now inside the scope of the function in which they were originally declared. The callback actually fires OUTSIDE this function, so scope is lost.

Here is a sample script to show all the elements you should be aware of. The () brackets after the function mean that I am immediately executing the function.
var one = 1;
var two = 2;

var a = function changeOneAndTwo()
{
   one = "1.0"; // changes global variable
   var two = "2.0"; // this stays local
}() 

alert( "one="+one+", two="+two);  // one=1.0, two=2

three = 3
four = 4

var b = function changeThreeAndFour()
{
  var three = "3.0"; // remains local
  four = "4.0" // global
}()

alert( "three="+three+", four="+four); // three=3, 4=4.0

var c = function setFiveAndSix()
{
  var five = 5;
  six = 6; // this is GLOBAL
}()

var d = function changeFiveAndSix()
{
   five = "5.0"; // this is GLOBAL
   var six = "6.0"; //this is local
}()

var f = function displayFiveAndSix()
{
 alert("five="+five) // five=5.0
 alert("six="+six);  // six=6
}()

No comments:

Post a Comment