LEARNING JAVASCRIPT - Trang 144

scope. Let’s consider a simple example: keeping track of information about a user.

Your program keeps track of a user’s name and age, and there are some functions that

operate on that information. One way to do this is with global variables:

let

name

=

"Irena"

;

// global

let

age

=

25

;

// global

function

greet

() {

console.log(

`Hello,

${

name

}

!`

);

}

function

getBirthYear

() {

return

new

Date

().

getFullYear

()

-

age

;

}

The problem with this approach is that our functions are highly dependent on the

context (or scope) that they’re called from. Any function—anywhere in your entire

program—could change the value of

name

(accidentally or intentionally). And “name”

and “age” are generic names that might reasonably be used elsewhere, for other rea‐

sons. Because

greet

and

getBirthYear

rely on global variables, they are basically

relying on the rest of the program using

name

and

age

correctly.

A better approach would be to put user information in a single object:

let

user

=

{

name

=

"Irena"

,

age

=

25

,

};

function

greet

() {

console.log(

`Hello,

${

user

.

name

}

!`

);

}

function

getBirthYear

() {

return

new

Date

().

getFullYear

()

-

user

.

age

;

}

In this simple example, we’ve only reduced the number of identifiers in the global

scope by one (we got rid of

name

and

age

, and added

user

), but imagine if we had 10

pieces of information about the user…or 100.
We could do better still, though: our functions

greet

and

getBirthYear

are still

dependent on the global

user

, which can be modified by anything. Let’s improve

those functions so they’re not dependent on global scope:

function

greet

(

user

) {

console.log(

`Hello,

${

user

.

name

}

!`

);

}

function

getBirthYear

(

user

) {

return

new

Date

().

getFullYear

()

-

user

.

age

;

}

120 | 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.