Setting this explicitly
Every function has three built-in methods that let you pick this yourself:
fn.call(thisValue, a, b): call now, arguments listed one by one.fn.apply(thisValue, [a, b]): call now, arguments in an array (apply → array).fn.bind(thisValue): don't call. Returns a new function withthispermanently locked in.
call and apply are for one-off calls. bind is for handing a function to someone else to call later.
You need these the moment a function travels. Handing a method to setTimeout, to forEach, or to an event system is everyday code, and that hand-off is exactly where this gets lost — bind is the standard repair, so this bug (and its fix) shows up in nearly every interview loop.
Code exercise · javascript
Run it. One function, three different `this` values, chosen by the caller each time.
The classic bug: losing this in a callback
When you pass a method somewhere as a callback, like setTimeout(dog.speak, 100) or array.forEach(obj.method), the receiver later calls it as a plain function (Rule 2 from lesson 2-1). The dot is long gone, so this is lost.
Two standard fixes:
dog.speak.bind(dog): lockthisbefore handing it over.- Wrap it as
() => dog.speak(), so the arrow performs a real method call when invoked.
Code exercise · javascript
Run it. `runLater` calls whatever you give it as a plain function. The unbound version loses `this`, the bound one keeps it.
bind can also preset arguments
bind accepts arguments after the this value and locks those in too: multiply.bind(null, 2) returns a function whose first parameter is permanently 2 (the null just fills the this slot for a function that never uses this). Making a specific function out of a general one like this is called partial application.
apply has a classic use of its own: Math.max.apply(null, nums) hands an array to a function as separate arguments — for years this was the standard way to take the max of an array.
Code exercise · javascript
Run it. `double` is `multiply` with its first argument frozen to 2, and `apply` feeds the whole array to `Math.max` as individual arguments.
Quiz
What does `fn.bind(obj)` do?
Code exercise · javascript
Your turn. The notifier below prints `undefined: server down` because the method loses `this`. Fix the LAST line only, using `bind`, so it prints `pager: server down`.