HTML and CSS Reference
In-Depth Information
Scope and “this”
In order to fully understand a language, you must understand its approach to scoping vari-
ables. Understanding scope tells us when various variables are available within the program,
and which variable is used if there are multiple variables available with the same name.
Let's start with a simple example:
> function getNumber() {
num = 10;
return num;
}
This is a function that always returns the same number: 10.
> getNumber()
10
> getNumber()
10
When this function finishes execution, it may seem that the variable
num
would no longer
be available based on our discussion of function scoped variables earlier in this chapter. This
is not the case:
> num
10
This is because we forgot to use
var
when declaring the variable. If we had done the follow-
ing, the variable would not have existed after the function completed:
> function getNumber() {
var
num = 10;
return num;
}
Due to the fact
var
was omitted; the
num
variable was added as a property to the object
represented by a special variable called
this
. Within a function,
this
refers to a special object
called
window
. You can see this by typing
this
in the console: