1
It will either get bound to the global object or it will be
undefined
, depending on whether or not you are in
strict mode. We’re not covering all the details here because you should avoid this situation.
function doesn’t use
this
, we will generally refer to it as a function, no matter where
it’s declared.
One detail about the
this
variable that often trips people up is when you need to
access it in a nested function. Consider the following example, where we use a helper
function inside a method:
const
o
=
{
name
:
'Julie'
,
greetBackwards
:
function
() {
function
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
();
Here we’re using a nested function,
getReverseName
, to reverse the name. Unfortu‐
nately,
getReverseName
won’t work as we expect it to: when we call
o.greetBack
wards()
, JavaScript binds
this
as we expect. However, when we call
getReverseName
from inside
greetBackwards
,
this
will be bound to something else.
A common solu‐
tion to this problem is to assign a second variable to
this
:
const
o
=
{
name
:
'Julie'
,
greetBackwards
:
function
() {
const
self
=
this
;
function
getReverseName
() {
let
nameBackwards
=
''
;
for
(
let
i
=
self
.
name
.
length
-
1
;
i
>=
0
;
i
--
) {
nameBackwards
+=
self
.
name
[
i
];
}
return
nameBackwards
;
}
return
`
${
getReverseName
()
}
si eman ym ,olleH`
;
},
};
o
.
greetBackwards
();
The this Keyword | 111