LEARNING JAVASCRIPT - Trang 148

Consider the important implications of this: when we call

globalFunc

, it has access to

blockVar

despite the fact that we’ve exited that scope. Normally, when a scope is exited,

the variables declared in that scope can safely cease to exist. Here, JavaScript notes

that a function is defined in that scope (and that function can be referenced outside of

the scope), so it has to keep the scope around.
So defining a function within a closure can affect the closure’s lifetime; it also allows

us to access things we wouldn’t normally have access to. Consider this example:

let

f

;

// undefined function

{

let

o

=

{

note

:

'Safe'

};

f

=

function

() {

return

o

;

}
}

let

oRef

=

f

();

oRef

.

note

=

"Not so safe after all!"

;

Normally, things that are out of scope are strictly inaccessible. Functions are special

in that they allow us a window into scopes that are otherwise inaccessible. We’ll see

the importance of this in upcoming chapters.

Immediately Invoked Function Expressions

In

Chapter 6

, we covered function expressions. Function expressions allow us to cre‐

ate something called an immediately invoked function expression (IIFE). An IIFE

declares a function and then runs it immediately. Now that we have a solid under‐

standing of scope and closures, we have the tools we need to understand why we

might want to do such a thing. An IIFE looks like this:

(

function

() {

// this is the IIFE body

})();

We create an anonymous function using a function expression, and then immediately

call (invoke) that function. The advantage of the IIFE is that anything inside it has its

own scope, and because it is a function, it can pass something out of the scope:

const

message

=

(

function

() {

const

secret

=

"I'm a secret!"

;

return

`The secret is

${

secret

.

length

}

characters long.`

;

})();

console

.

log

(

message

);

The variable

secret

is safe inside the scope of the IIFE, and can’t be accessed from

outside. You can return anything you want from an IIFE, and it’s quite common to

return arrays, objects, and functions. Consider a function that can report the number

of times it’s been called in a way that can’t be tampered with:

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