LEARNING JAVASCRIPT - Trang 142

Scope Versus Existence

It’s intuitively obvious that if a variable doesn’t exist, it’s not in scope. That is, variables

that have not yet been declared, or variables that have ceased to exist because a func‐

tion exits, are clearly not in scope.
What about the converse? If a variable is not in scope, does that mean it doesn’t exist?

Not necessarily, and this is where we must make a distinction between scope and exis‐

tence.
Scope (or visibility) refers to the identifiers that are currently visible and accessible by

the currently executing part of the program (called the execution context). Existence,

on the other hand, refers to identifiers that hold something for which memory has

been allocated (reserved). We’ll soon see examples of variables that exist but are not

in scope.
When something ceases to exist, JavaScript doesn’t necessarily reclaim the memory

right away: it simply notes that the item no longer needs to be kept around, and the

memory is periodically reclaimed in a process called garbage collection. Garbage col‐

lection in JavaScript is automatic, and outside of certain highly demanding applica‐

tions, isn’t something you’ll need to concern yourself with.

Lexical Versus Dynamic Scoping

When you look at the source code for a program, you are looking at its lexical struc‐

ture. When the program actually runs, execution can jump around. Consider this

program with two functions:

function

f1

() {

console

.

log

(

'one'

);

}

function

f2

() {

console

.

log

(

'two'

);

}

f2

();

f1

();

f2

();

Lexically, this program is simply a series of statements that we generally read from

top to bottom. However, when we run this program, execution jumps around: first to

the body of function

f2

, then to the body of function

f1

(even though it’s defined

before

f2

), then back to the body of function

f2

.

Scoping in JavaScript is lexical, meaning we can determine what variables are in scope

simply by looking at the source code. That’s not to say that scope is aways immedi‐

118 | Chapter 7: Scope

Liên Kết Chia Sẽ

** Đây là liên kết chia sẻ bới cộng đồng người dùng, chúng tôi không chịu trách nhiệm gì về nội dung của các thông tin này. Nếu có liên kết nào không phù hợp xin hãy báo cho admin.