LEARNING JAVASCRIPT - Trang 136

2

A so-called “immediately invoked function expression” (IIFE), which we will cover in

Chapter 7

.

This is a common technique, and you will see

this

get assigned to

self

or

that

.

Arrow functions, which we’ll see later in this chapter, are another way of addressing

this problem.

Function Expressions and Anonymous Functions

So far, we’ve been dealing exclusively with function declarations, which give functions

both a body (which defines what the function does) and an identifier (so we can call it

later). JavaScript also supports anonymous functions, which don’t necessarily have an

identifier.
You might reasonably be wondering what use is a function without an identifier.

Without an identifier, how are we to call it? The answer lies in understanding function

expressions. We know that an expression is something that evaluates to a value, and

we also know that functions are values like any other in JavaScript. A function expres‐

sion is simply a way to declare a (possibly unnamed) function. A function expression

can be assigned to something (thereby giving it an identifier), or called immediately.

2

Function expressions are syntactically identical to function declarations except that

you can omit the function name. Let’s consider the example where we use a function

expression and assign the result to a variable (which is effectively equivalent to a

function declaration):

const

f

=

function

() {

// ...

};

The outcome is the same as if we had declared the function in the usual way: we’re

left with an identifier

f

that refers to a function. Just as with regular function declara‐

tion, we can call the function with

f()

. The only difference is that we are creating an

anonymous function (by using a function expression) and assigning it to a variable.
Anonymous functions are used all the time: as arguments to other functions or meth‐

ods, or to create function properties in an object. We will see these uses throughout

the book.
I said that the function name is optional in a function expression…so what happens

when we give the function a name and assign it to a variable (and why would we want

to do this)? For example:

const

g

=

function

f

() {

// ...

}

112 | Chapter 6: Functions

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.