spacer
Yehuda Shiran March 24, 2001
The Scope of Function Code
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

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:

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