When you call a function in javascript, 'this' will refer to different things depending on the context:
If the function has been bound, the 'this' will be set to whatever
it was bound to, e.g. fn.bind(x)()
If you invoked the function using fn.call(x)
or fn.apply(x)
, the
this will be set to x.
If the function was defined using arrow notation, then the this
will be whatever was defined to be this
when the function was
defined.
If you call the function with thing.fn()
, the this
is what is
before the '.', in this case 'thing'.
If you're in a constructor, called with new
then this
refers to
the new object under construction.
If you are just calling a bare function, that isn't on any object,
that isn't bound, that isn't an arrow function and you're calling it
in the straightforward way, without using call or apply, then the
this
will refer to the global object if you are not in strict mode,
and undefined if you are in strict mode. This is what is referred to
as 'this coercion' by the quote.
That's why, if you open a browser console and type
Function('console.log(this)')()
the console will output the Window which is the global object in the browser. However if you open the console and type
Function('"use strict";console.log(this)')()
the console will log undefined
.
I'm using the Function constructor here, because it's a way to force the use of non-strict mode regardless of the situation it appears in - so these examples should still work, even if you run them from inside a file or console operating in strict mode.
this
coercion can be the the most convenient way of getting the global object, i.e.
const global = Function('return this')()
works in both the browser and node, even in strict mode.
But most of the time, you want to fail fast, and having functions that you expected to operate on specific kinds of instances actually operate on your global object can mess things up badly. Having attempts to write something to or read something from this
throw exceptions when it isn't defined is almost always better than reading and writing to the global object.