LEARNING JAVASCRIPT - Trang 139

const

bruce

=

{

name

:

"Bruce"

};

const

madeline

=

{

name

:

"Madeline"

};

// this function isn't associated with any object, yet
// it's using 'this'!

function

greet

() {

return

`Hello, I'm

${

this

.

name

}

!`

;

}

greet

();

// "Hello, I'm !" - 'this' not bound

greet

.

call

(

bruce

);

// "Hello, I'm Bruce!" - 'this' bound to 'bruce'

greet

.

call

(

madeline

);

// "Hello, I'm Madeline!" - 'this' bound to 'madeline'

You can see that

call

allows us to call a function as if it were a method by providing

it an object to bind

this

to. The first argument to

call

is the value you want

this

bound to, and any remaining arguments become arguments to the function you’re

calling:

function

update

(

birthYear

,

occupation

) {

this

.

birthYear

=

birthYear

;

this

.

occupation

=

occupation

;

}

update

.

call

(

bruce

,

1949

,

'singer'

);

// bruce is now { name: "Bruce", birthYear: 1949,

// occupation: "singer" }

update

.

call

(

madeline

,

1942

,

'actress'

);

// madeline is now { name: "Madeline", birthYear: 1942,

// occupation: "actress" }

apply

is identical to

call

except the way it handles function arguments.

call

takes

arguments directly, just like a normal function.

apply

takes its arguments as an array:

update

.

apply

(

bruce

, [

1955

,

"actor"

]);

// bruce is now { name: "Bruce", birthYear: 1955,

// occupation: "actor" }

update

.

apply

(

madeline

, [

1918

,

"writer"

]);

// madeline is now { name: "Madeline", birthYear: 1918,

// occupation: "writer" }

apply

is useful if you’ve got an array and you want to use its values as arguments to a

function. The classic example is finding the minimum or maximum number in an

array. The built-in

Math.min

and

Math.max

functions take any number of arguments

and return the minimum or maximum, respectively. We can use

apply

to use these

functions with an existing array:

const

arr

=

[

2

,

3

,

-

5

,

15

,

7

];

Math

.

min

.

apply

(

null

,

arr

);

// -5

Math

.

max

.

apply

(

null

,

arr

);

// 15

Note that we simply pass

null

in for the value of

this

. That’s because

Math.min

and

Math.max

don’t use

this

at all; it doesn’t matter what we pass in here.

call, apply, and bind | 115

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.