LEARNING JAVASCRIPT - Trang 138

const

f1

=

function

() {

return

"hello!"

; }

// OR

const

f1

=

()

=>

"hello!"

;

const

f2

=

function

(

name

) {

return

`Hello,

${

name

}

!`

; }

// OR

const

f2

=

name

=>

`Hello,

${

name

}

!`

;

const

f3

=

function

(

a

,

b

) {

return

a

+

b

; }

// OR

const

f3

=

(

a

,

b

)

=>

a

+

b

;

These examples are a bit contrived; usually, if you need a named function, you would

simply use a regular function declaration. Arrow functions are most useful when

you’re creating and passing around anonymous functions, which we’ll see quite often

starting in

Chapter 8

.

Arrow functions do have one major difference from regular functions:

this

is bound

lexically, just like any other variable. Recall our

greetBackwards

example from earlier

in the chapter. With an arrow function, we can use

this

inside the inner function:

const

o

=

{

name

:

'Julie'

,

greetBackwards

:

function

() {

const

getReverseName

=

()

=>

{

let

nameBackwards

=

''

;

for

(

let

i

=

this

.

name

.

length

-

1

;

i

>=

0

;

i

--

) {

nameBackwards

+=

this

.

name

[

i

];

}

return

nameBackwards

;

};

return

`

${

getReverseName

()

}

si eman ym ,olleH`

;

},
};

o

.

greetBackwards

();

Arrow functions have two additional minor differences from regular functions: they

can’t be used as object constructors (see

Chapter 9

), and the special

arguments

vari‐

able isn’t available in arrow functions (which is no longer necessary thanks to the

spread operator).

call, apply, and bind

We’ve already seen the “normal” way

this

is bound (which is consistent with other

object-oriented languages). However, JavaScript allows you to specify what

this

is

bound to no matter how or where the function in question is called. We’ll start with

call

, which is a method available on all functions that allows you to call the function

with a specific value of

this

:

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