spacer
Yehuda Shiran March 19, 2001
Accessing Globals from an Object
Tips: March 2001

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
Eclipse Helios Update Brings New PHP Tools
Internet Explorer 9 Ups Standards Support
JBoss Portal 5 Release Easier to Use

There are at least three different ways to define a function in JavaScript. They are all equivalent in their way of treating global variables. They can modify global variables from the outside context. This statement is no longer true when you define an object's methods. We initialize a global variable to 5, and each function definition below adds 10 to it inside the function definition. The traditional and anonymous definitions do modify the global variable, but the constructor definition does not. In fact, you get an error message when trying to access a global variable from inside the constructor definition. Notice that each click below will increment the global variable by 10. Here are the class and object definitions, line-wrapped here for better readability on this page:

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

  this.third = new Function(
   "param", 
   " global += 10; alert(param + ' method shows global to be ' + global)");
}
var x = new myGlobal();

Let's try calling all methods: traditional, anonymous, and constructor.


People who read this tip also read these tips:

Look for similar tips by subject:

webref The latest from WebReference.com Browse >
Flashmaps' DynamicLocator: Interactive Maps for Small Areas · Flashmaps' AreaSelector: Interactive Maps for Wide Areas · The DB Mapper: Interactive Street-level Maps of U.S. and Canada
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
MS Access and MySQL · Cisco AutoQoS: VoIP QoS for Mere Mortals · While VoIP Adoption Explodes in Enterprise, Carrier Spending Lags