LEARNING JAVASCRIPT - Trang 129

Or assign a function to an object property:

const

o

=

{};

o

.

f

=

getGreeting

;

o

.

f

();

// "Hello, World!"

Or even add a function to an array:

const

arr

=

[

1

,

2

,

3

];

arr

[

1

]

=

getGreeting

;

// arr is now [1, function getGreeting(), 2]

arr

[

1

]();

// "Hello, World!"

This last example should make clear the role of the parentheses: if JavaScript encoun‐

ters parentheses that follow a value, the value is assumed to be a function, and that

function is called. In the preceding example,

arr[1]

is an expression that resolves to a

value. That value is followed by parentheses, which is a signal to JavaScript that the

value is a function and should be called.

If you try to add parentheses to a value that is not a function, you

will get an error. For example, "whoops"() will result in the error
TypeError: "whoops" is not a function

.

Function Arguments

We’ve now seen how to call functions and get values out of them; how about getting

information into them? The primary mechanism to pass information to a function

call is function arguments (sometimes called parameters). Arguments are like vari‐

ables that don’t exist until the function is called. Let’s consider a function that takes

two numeric arguments and returns the average of those numbers:

function

avg

(

a

,

b

) {

return

(

a

+

b

)

/

2

;

}

In this function declaration,

a

and

b

are called formal arguments. When a function is

called, formal arguments receive values and become actual arguments:

avg

(

5

,

10

);

// 7.5

In this example, the formal arguments

a

and

b

receive the values

5

and

10

, and

become actual arguments (which are very much like variables, but specific to the

function body).
One thing that beginners often stumble over is that the arguments exist only in the

function, even if they have the same name as variables outside of the function.

Consider:

Function Arguments | 105

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.