LEARNING JAVASCRIPT - Trang 134

const

o

=

{

name

:

'Wallace'

,

// primitive property

bark

() {

return

'Woof!'

; },

// function property (method)

}

The this Keyword

Inside a function body, a special read-only value called

this

is available. This key‐

word is normally associated with object-oriented programming, and we will be learn‐

ing more about its use in that context in

Chapter 9

. However, in JavaScript, it can be

used in multiple ways.
Normally, the

this

keyword relates to functions that are properties of objects. When

methods are called, the

this

keyword takes on the value of the specific object it was

called on:

const

o

=

{

name

:

'Wallace'

,

speak

() {

return

`My name is

${

this

.

name

}

!`

; },

}

When we call

o.speak()

, the

this

keyword is bound to

o

:

o

.

speak

();

// "My name is Wallace!

It’s important to understand that

this

is bound according to how the function is

called, not where the function is declared. That is,

this

is bound to

o

not because

speak

is a property of

o

, but because we called it directly on

o

(

o.speak

). Consider

what happens if we assign that same function to a variable:

const

speak

=

o

.

speak

;

speak

===

o

.

speak

;

// true; both variables refer to the same function

speak

();

// "My name is !"

Because of the way we called the function, JavaScript didn’t know that the function

was originally declared in

o

, so

this

was bound to

undefined

.

If you call a function in such a way that it’s not clear how to bind
this

(such as calling the function variable speak as we did previ‐

ously), what this gets bound to is complex. It depends on whether

you’re in strict mode or not, and where the function is being called

from. We are intentionally glossing over these details because it’s

best to avoid this situation. If you want to know more, see the

MDN documentation for

code formatting

.

The term method is traditionally associated with object-oriented programming, and

in this book, we’ll use it to mean a function that is a property of an object and is

designed to be called directly from an object instance (such as

o.speak()

) above. If a

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