spacer
Yehuda Shiran March 18, 2001
Modifying Globals
Tips: March 2001

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
News Flash: Adobe Has iPhone Workaround
Adobe's Flash 10.1 Goes Mobile (Minus iPhone)
A Salute to Visionary CEOs

There are at least three different ways to define a function in JavaScript. They are all equivalent in the way they treat global variables. They can modify global variables from the outside context. We initialize a global variable to 5, and each function definition below adds 10 to it inside the function definition. We then print its value. Notice that each click below will increment the global variable by 10. Here is the traditional definition:

var global = 5;
function first(param) {
  global += 10;
  alert(param + " method shows global to be " + global);
}

Pass "first" to this function and see that you get the expected alert box with the global variable incrementing by 10. The second way to define a function is the anonymous way. You define a function inline, without giving it a name:

second = function(param) {
   global += 10; 
   alert(param + " method shows global to be " + global)
};

Pass "second" to this function and see that you get the expected alert box, with the global variable incrementing by 10. The third way to define a function is by constructing it with the Function function. The Function function accepts two parameters: the parameter to be passed, and the body of the function:

third = new Function(
   "param", 
   " global += 10; alert(param + ' method shows global to be ' + global)");

Pass "third" to this function and see that you get the expected alert box, showing global incrementing by 10 with each click.


People who read this tip also read these tips:

Look for similar tips by subject:

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Building a Banking Application Home Page with OOP · Mixing Scripting Languages · Review: phpFox, a Social Networking CMS with all the Bells and Whistles
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Enterprise 2.0: Social Networking in the Cloud · BroadSoft Marketplace Hastens Pace of Telephony Innovation · Review: HTC Hero for Sprint