In this video, Mei writes one reminder() function for her plants in a new module in her plant-tracker folder, and calls it four different ways. Each time, the form of the call, or a binding made with .bind(), decides what this is inside the function.
Key Points
- A method call (
goldie.reminder("Monday")):thisis the object before the dot,goldie. - A plain call (
reminder("Friday")): there’s no dot, so there’s no object. Your file is a module, so it’s strict, andthisisundefined. Readingthis.namethen throws aTypeError, and the script stops. .call()and.apply(): functions are values, and every function has built-in methods.reminder.call(spike, "Sunday")makesspikethethisfor that one call and passes the rest of the arguments as usual..apply()does the same job but takes the function’s arguments in an array:reminder.apply(spike, ["Sunday"]). Spike’s record stays plain data and never needs areminderproperty.- A bound function:
reminder.bind(spike)doesn’t callreminder(). It returns a new function whosethisis fixed tospike. It always callsreminder()withthisset tospike, so even with no dot, as inspikeReminder("Saturday"),thisis stillspike. - The rule: to find
this, first check whether the function is bound. If it is,thisis the object it was bound to. If not, look at the call. Where a function is written decides which variables it can see. But for a function written with thefunctionkeyword, likereminder(), or a shorthand method, likeneedsWater(),thiscomes from the call, or from.bind(). Arrow functions are the exception. They work differently, and you’ll see how later in this course.
| The call | this is |
|---|---|
spikeReminder(), from reminder.bind(spike) (check first) |
spike, the object it was bound to |
goldie.reminder() |
goldie, the object before the dot |
reminder() |
undefined (strict code) |
reminder.call(spike), reminder.apply(spike) |
spike, the first argument |