LEARNING JAVASCRIPT - Trang 143

ately obvious from the source code: we’ll see some examples in this chapter that

require close examination to determine scope.
Lexical scoping means whatever variables are in scope where you define a function

from (as opposed to when you call it) are in scope in the function. Consider this

example:

const

x

=

3

;

function

f

() {

console

.

log

(

x

);

// this will work

console

.

log

(

y

);

// this will cause a crash

}

const

y

=

3

;

f

();

The variable

x

exists when we define the function

f

, but

y

doesn’t. Then we declare

y

and call

f

, and see that

x

is in scope inside the body of

f

when it’s called, but

y

isn’t.

This is an example of lexical scoping: the function

f

has access to the identifiers that

were available when it was defined, not when it was called.
Lexical scoping in JavaScript applies to global scope, block scope, and function scope.

Global Scope

Scope is hierarchical, and there has to be something at the base of the tree: the scope

that you’re implicitly in when you start a program. This is called global scope. When a

JavaScript program starts—before any functions are called—it is executing in global

scope. The implication is, then, that anything you declare in global scope will be avail‐

able to all scopes in your program.
Anything declared in global scope is called a global, and globals have a bad reputa‐

tion. It’s hard to crack open a book about programming without being warned that

using globals will cause the very earth to split open and swallow you whole. So why

are globals so bad?
Globals are not bad—as a matter of fact, they are a necessity. What’s bad is the abuse

of the global scope. We already mentioned that anything available in global scope is

therefore available in all scopes. The lesson there is to use globals judiciously.
The clever reader might think “well, I will create a single function in the global scope,

and therefore reduce my globals to one!” Clever, except you’ve now just moved the

problem one level down. Anything declared in the scope of that function will be

available to anything called from that function…which is hardly better than global

scope!
The bottom line is this: you will probably have things that live in global scope, and

that’s not necessarily bad. What you should try to avoid is things that rely on global

Global Scope | 119

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.