1. Computing

JavaScript By Example

Browser Object Model: 1. window

By

When JavaScript is run in a web browser the window object is defined as having global scope (this object is not automatically created when JavaScript is run outside of a browser). Many of the objects that JavaScript creates and everything that you create in your script that has global scope are then created as properties and methods of the window object.

By taking advantage of the fact that all your globally defined variables are actually properties of window you can do a number of things that would not be possible if this were not the case. One possibility is where you have a local variable with the same name as a global variable where the name by itself refers to the local variable. Simply add window. to the front to reference the global variable. Another option (which does away with most of the situations where you would otherwise need to use eval) is that you cal also use the alternate window[] notation which allows you to dynamically specify the variable name (as the following example demonstrates by setting y equal to 3).


var x, y;
setField = function(fld, val) {
window[fld] = val;
};
 
x = 'y';
setField(x,3);

Reader Submissions: Help Others By Providing Your Own JavaScript Examples

JavaScript By Example
  1. About.com
  2. Computing
  3. JavaScript
  4. Javascript Tutorials
  5. JavaScript By Example
  6. Browser Object Model
  7. JavaScript By Example - BOM: window

©2014 About.com. All rights reserved.