LEARNING JAVASCRIPT - Trang 131

between primitives and objects. Primitives can’t be modified (we can change the value

of a primitive variable, but the primitive value itself doesn’t change). Objects, on the

other hand, can be modified.
Let’s be clear here: the

o

inside the function is separate and distinct from the

o

outside

of the function, but they both refer to the same object. We can see that difference again

with assignment:

function

f

(

o

) {

o

.

message

=

"set in f"

;

o

=

{

message

:

"new object!"

};

console.log(

`inside f: o.message="

${

o

.

message

}

" (after assignment)`

);

}

let

o

=

{

message

:

'initial value'

};

console.log(

`before calling f: o.message="

${

o

.

message

}

"`

);

f

(

o

);

console.log(

`after calling f: o.message="

${

o

.

message

}

"`

);

If you run this example, you will see:

before calling f: o.message="initial value"
inside f: o.message="new object!" (after assignment)
after calling f: o.message="set in f"

The key to understanding what’s going on here is understanding that the argument

o

(inside the function) is different than the variable

o

(outside the function). When

f

is

called, both point to the same object, but when

o

is assigned inside

f

, it points to a

new, distinct object. The

o

outside the function still points to the original object.

Primitives in JavaScript are considered value types in computer sci‐

ence parlance, because when they are passed around, the value is

copied. Objects are called reference types because when they are

passed around, both variables refer to the same object (that is, they

both hold a reference to the same object).

Do Arguments Make the Function?

In many languages, a function’s signature includes its arguments. For example, in C,

f()

(no arguments) is a different function than

f(x)

(one argument), which is a dif‐

ferent function than

f(x, y)

(two arguments). JavaScript makes no such distinction,

and when you have a function named

f

, you can call it with 0 or 1 or 10 arguments,

and you’re calling the same function.

Function Arguments | 107

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.