this

Abbreviations
*[JS]: JavaScript
Introduction
In this subunit, we'll tackle the most confusing word in JavaScript—the keyword this, this is only four letters, but it will take a whole subunit to understand. Make a note; this is a favorite topic that interviewers love to quiz prospective employees about. We'll dive deep into what the keyword this refers to and how you can easily determine its value.
Goals
Learn how to stop worrying and love the keyword this
Explain what .call does
Explain what .bind does
Use .call and .bind to reassign the value of the keyword this
This and Bind
This
Mystery of the Undefined Fluffy
demo/fluffy.js
makes sense
wtf?
JavaScript Functions
In a sense, JavaScript doesn't have functions.
Everything is called on something
Global Object
When you call a function on nothing...
... you call it on the "global object"
In browser JS, that's window (the browser window)
in Node.js, that's global (where some Node utilities are)
You relied on that, even if you didn't realize it!
Therefore, a "function" called at the top level is the same as:
Undefined Fluffy
demo/fluffy.js
so... what's happening here?
Find the dance method on fluffy
Call the dance method on fluffy - yay!
Find the dance method on fluffy
Call the dance method on the global window - ut oh!
call
Sometimes, you'll need to say "call this function on this object"
That's what call()
is for!
NOTE: apply()
There is a related function, apply()
: for this, you can pass the list of arguments to the function as an array, rather than passing one-by-one.
This used to be a crucial technique, since it was the only reasonable way to call a function that expected several individual arguments where you already had those arguments in a list:
Nowadays, however, this is much easily done with the spread operator:
Bind
You can "perma-bind" a function to a context
bind
is a method on functions that returns a bound copy of the function
Binding Arguments
You can also bind arguments to functions. That will bake them into the function.
Where This Comes Up
Callback on Methods
Want to have object method as callback:
That won't work - browser will call dance on a global object. 😦
That will work — when it calls that callback, it will always be on Fluffy!
Pre-Binding Calls
Imagine we want three buttons which call popUp, but with different args:
demo/buttons-meh.html
demo/buttons-meh.js
Arrow Functions
Arrow functions don’t make their own this
demo/timeout.js