Variable Scope

JavaScript offers two scopes for variables:

  • Global within the current window (defined with or without var)

  • Local within the current function (must be defined with var)

Function statements can get and set all global variables, but can get and set only local variables defined within the same function. The system is pretty simple, if loose. If you forget to use the var keyword while defining a local variable, it becomes a global variable. Even an external JavaScript library can define a global variable as it loads into the browser. But when you load a new page into the browser, all variables from the previous page are gone and scripts in the new page start over.

The scope situation becomes a bit more complex in C and Objective-C because programs usually consist of multiple files, many of which are capable of generating object instances that are intended to encapsulate their data (with the help of instance variables).

Instance Variables

An instance variable defined in a class header file is visible to all statements and methods defined in the same class. It’s not global as in “global for the entire application code,” but certainly for all code in the same class. If you create a subclass, the subclass also inherits the instance variable, which is therefore accessible to methods defined in the subclass.

It’s important to remember from your JavaScript object creation experience that an instance variable has scope only within its single instance. If you define two instances of the ...

Get Learning the iOS 4 SDK for JavaScript Programmers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.