this and Function Binding
Build a precise mental model of JavaScript values, scope, functions, objects, arrays and asynchronous behavior, then implement and debug real utilities from first principles instead of memorizing outputs.
What you will be able to do
#- Predict this from the call site rather than the definition.
- Use call, apply and bind to set this explicitly.
- Explain why arrow functions capture this lexically.
Overview
#this is decided at the call site
For a regular function, this is determined by how the function is called, not where it is defined. A method call sets this to the receiver, a plain call sets it to undefined in strict mode or the global object otherwise, and a call with new sets it to the newly created object.
const counter = {
count: 0,
inc() { this.count += 1; return this.count; }
};
console.log(counter.inc()); // 1
const inc = counter.inc;
console.log(inc()); // NaN or throws, this is not counter
Explicit binding
call and apply invoke the function immediately with a chosen this, and apply takes the arguments as an array. bind returns a new function with this fixed, which is the tool for passing a method as a callback.
const bound = counter.inc.bind(counter);
console.log(bound()); // 2
Arrow functions
An arrow function has no this of its own. It captures the this of the enclosing scope, which is why it is the right choice for callbacks inside a method but the wrong choice for a method that needs a dynamic this.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
What does this line print?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.javascriptconst obj = { value: 7, get() { return this.value; } }; const fn = obj.get; console.log(obj.get(), fn === undefined ? 'x' : typeof fn);Exercise 2Explain
Explain why an arrow function inside a method keeps the method's this but a nested regular function does not.
starter.textconst obj = { value: 1, run() { const arrow = () => this.value; const fn = function () { return this.value; }; return [arrow(), fn()]; } };Reveal the reference answer
reference.textAn arrow function does not create its own this, so it uses the this of run, which is obj, and returns 1. A nested regular function gets its own this from how it is called; calling it plainly gives undefined in strict mode, so this.value is undefined or throws. The arrow inherits, the regular function rebinds.Authored expected output: [1, undefined]
The answer should state that arrows capture the enclosing this and regular functions get this from the call site.
Exercise 3Implement
Implement `bindTo(obj, method)` so it returns a function that always calls method with obj as this and forwards arguments.
starter.javascriptfunction bindTo(obj, method) { // your code here }Reveal the reference answer
reference.javascriptfunction bindTo(obj, method) { return function (...args) { return method.apply(obj, args); }; }Authored expected output: a function whose this is always obj
The returned closure ignores its own this and uses apply to call method with the captured obj and the forwarded arguments.
Exercise 4Debug
This timer is meant to increment the counter but logs NaN. Find and fix the bug.
starter.javascriptconst counter = { count: 0, start() { setInterval(function () { this.count += 1; console.log(this.count); }, 1000); } }; counter.start();Reveal the reference answer
reference.javascriptconst counter = { count: 0, start() { setInterval(() => { this.count += 1; console.log(this.count); }, 1000); } }; counter.start();Authored expected output: 1 2 3 ...
The timer calls the regular function with this set to undefined or the global object, so this.count is not the counter's count. An arrow function captures the this of start, which is counter.
Exercise 5Test
Write assertions that prove call and apply both set this while bind returns a new function.
starter.javascriptfunction assertEqual(actual, expected, label) { if (actual !== expected) throw new Error(label + ': expected ' + expected + ' but got ' + actual); }Reveal the reference answer
reference.javascriptfunction who() { return this.name; } assertEqual(who.call({ name: 'a' }), 'a', 'call sets this'); assertEqual(who.apply({ name: 'b' }), 'b', 'apply sets this'); const bound = who.bind({ name: 'c' }); assertEqual(typeof bound, 'function', 'bind returns a function'); assertEqual(bound(), 'c', 'bound function keeps this'); console.log('all assertions passed');Authored expected output: all assertions passed
call and apply run immediately with the given this, while bind returns a new function with this fixed for later calls.
Exercise 6Interview
How do you avoid losing this when passing a method as a callback?
Reveal the reference answer
reference.textI bind the method once, either with bind in the constructor or by declaring the method as an arrow class field, so the this is fixed at creation. I avoid passing a bare method reference into setTimeout or an event listener, because the call site then decides this. When I only need the behavior, I pass a small arrow wrapper that calls the method on the intended object.The answer should name bind or arrow class fields, avoid bare method references, and mention a wrapper as an alternative.
Common misconceptions
#- this refers to the function that is running.
- bind calls the function immediately.
- Arrow functions have their own this.
Follow-up practice
#- javascript-foundations-objects-and-prototypes
- javascript-foundations-functional-programming-and-currying
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.