Examples: Defining Functions in Different Scopes

When using a with statement to set the script scope, functions defined within the with statement become visible for that object.

Example—Using a with statement:

// MyButton
With (YourButton)
{
  function square(value)
  {
    return value*value;
  }
  Alert (“The square of 3 equals “+ square(3))
}


// YourButton
var retVal = square(3)
Alert (“The square of 3 equals “+ retVal)

Explicitly defining the square function within the context of the YourButton object makes the function visible to scripts that are running behind the button. Any object from the object model can be used with the with statement.

Example—Dynamically adding a method to an object:

// MyButton
Function square(value)
  {
    return value*value;
  }
Alert (“The square of 3 equals “+ square(3))YourButton.square = square;


// YourButton
var retVal = square(3)
Alert (“The square of 3 equals “+ retVal)

A new method is added dynamically to the YourButton object. Scripts running in the context of this object can access the dynamically created square function.

Example—Assigning a value to a global variable:

// MyButton
Function square(value)
  {
    return value*value;
  }
Alert (“The square of 3 equals “+ square(3)) MyGlobalFunction = square;


// YourButton
var retVal = MyGlobalFunction(3)
Alert (“The square of 3 equals “+ retVal)

Creating a variable named MyGlobalFunction without using the var statement places the variable in the top scope. Thus, the variable is global.