spacer
Yehuda Shiran March 24, 2001
The Scope of Function Code
Tips: March 2001

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
OpenOffice 3.2 Lands Amid Critical Changes
Red Hat, IBM Firmly in KVM Virtualization Camp
Red Hat Talks Up Open Source Cloud Plans

Function code is code in the body of a function. The scope of function code is not trivial. It includes:
  • The variable object of the calling code's execution context. This object includes all variables that were defined up to the point where the function (or its outer function) is called.
  • The variable object of the outer function, if there is an outer function.
  • The global object which is the browser window object.
  • The arguments object which includes all passed parameter values.

A new variable object is created and initially has only the declared arguments of the function. Normally, the this object is the global object (the browser window object). The most obvious exception is when the function is a method of an object. In this case, the this value is the object that it is a method of. Let's examine an example. The function standAlone() just prints the value of this.location, where this is the browser window object. The function also prints window.location to show you that this is window. Try it.

The function ObjectConstructor() is an object constructor. We create a new object, newObject, with this constructor. Inside the constructor, the value of this.location is now undefined because this is the object newObject and not the browser window object. Try it

Here is the code:

function standAlone() {
  alert("this.location is " + this.location);
  alert("window.location is " + window.location);
}

function ObjectConstructor() {
  alert(this.location);
}

function createObj() {
  var newObject = new ObjectConstructor();
}

standAlone();


People who read this tip also read these tips:

Look for similar tips by subject:


The Network for Technology Professionals

Search:

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers

webref The latest from WebReference.com Browse >
Search Engine Optimization: Selecting and Embedding Keywords · Are Google's Language Translation Web Services Ready for Prime Time? · Installing and Using Meeplace, the Business Review CMS
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Workers Say Telework Is More Productive, Bosses Not So Sure · Kingston Debuts Power-Saving Memory Upgrades · Social Networking is King: Facebook Edges Google