Sub topic 15
Closures, this, and Arrow Functions
This chapter assumes you know how closures capture variables from enclosing scopes, as covered in earlier chapters. It also assumes you have used this inside object methods and constructors, and that you know what call, apply, and bind do in general.
Closures and this often get confused, because both seem to be "something a function remembers." They follow different rules. A closure captures variables through the scope chain, and that is fixed by where the code is written. A regular function's this is not a variable in the scope chain. It is set fresh each time the function is called, based on how it is called. Arrow functions are the exception: they have no this of their own, so they look this up through the scope chain the same way a closure looks up any other variable.
Why a Regular Inner Function Loses this
Every regular function (one written with the function keyword or method shorthand) gets its own this binding when it is invoked. An inner function never inherits the outer function's this, even though it can read every other outer variable.
'use strict';
const box = {
label: 'box',
describe() {
const prefix = 'Label:';
const inner = function () {
// prefix comes from the closure; this comes from the call below
return `${prefix} ${this === undefined ? '(no this)' : this.label}`;
};
return inner(); // plain call, so this is undefined in strict mode
}
};
console.log(box.describe()); // 'Label: (no this)'prefix resolves through the scope chain, so the closure finds it. this does not resolve through the scope chain. inner() is a plain call, so in strict mode its this is undefined. In sloppy mode it would be the global object, which hides the bug instead of reporting it.
The same thing happens with callbacks passed to timers, array methods, and event APIs. Whoever calls the callback decides its this, and that is almost never the object you wanted.
Three Ways to Keep the Outer this
Before arrow functions, developers used two workarounds. Both are still valid, and you will see them in older code.
'use strict';
function Counter() {
this.count = 0;
// 1. Capture this in an ordinary variable; the closure keeps it
const self = this;
setTimeout(function () {
self.count += 1;
console.log('self:', self.count);
}, 0);
// 2. Bind a new function whose this is fixed to the instance
setTimeout(function () {
this.count += 1;
console.log('bind:', this.count);
}.bind(this), 0);
// 3. Use an arrow function, which has no this of its own
setTimeout(() => {
this.count += 1;
console.log('arrow:', this.count);
}, 0);
}
new Counter();
// self: 1
// bind: 2
// arrow: 3The first fix shows the link to closures most clearly. self is an ordinary variable, so the callback captures it like any other variable. The arrow function does the same thing automatically: when the engine meets this inside an arrow, it walks outward to the nearest regular function (here Counter) and uses that function's this.
A Working Timer
The tutorial's Timer example uses an arrow callback inside setInterval. Here is a runnable version that stops itself, so the process can exit:
function Timer(limit) {
this.seconds = 0;
const id = setInterval(() => {
this.seconds += 1; // this is the Timer instance
console.log('tick', this.seconds);
if (this.seconds === limit) {
clearInterval(id); // id is captured by the closure too
}
}, 1000);
}
new Timer(3);
// tick 1
// tick 2
// tick 3The arrow callback closes over two things: the variable id through the normal scope chain, and the this of Timer through the same lexical lookup. Both stay reachable for as long as the interval is active.
Gotchas
Arrow Functions as Object Methods
Lexical this helps in callbacks and hurts in methods. An object literal does not create a scope, so an arrow function defined as a property takes this from the code around the object, not from the object itself.
const user = {
firstName: 'Ada',
greet() {
return `Hi, ${this.firstName}`;
},
greetArrow: () => `Hi, ${this.firstName}`
};
console.log(user.greet()); // 'Hi, Ada'
console.log(user.greetArrow()); // 'Hi, undefined' at the top level of a CommonJS fileAt the top level of an ES module, this is undefined, so greetArrow() throws a TypeError instead. Use method shorthand for methods that need the object.
call, apply, and bind Cannot Change an Arrow's this
An arrow's this is fixed when the arrow is created. Passing a different this is silently ignored.
'use strict';
function makeFns() {
return {
regular: function () { return this; },
arrow: () => this
};
}
const target = { id: 1 };
const owner = { makeFns };
const { regular, arrow } = owner.makeFns();
console.log(regular.call(target) === target); // true
console.log(arrow.call(target) === target); // false
console.log(arrow() === owner); // true, from makeFns's callThis matters with libraries that call your callback with a specific this. Older jQuery handlers and some test frameworks (Mocha's this.timeout()) rely on it. Passing an arrow function to them breaks that contract without any error.
Arrows Also Borrow arguments, super, and new.target
Arrow functions have no arguments object, no super, and no new.target of their own. All of them resolve lexically, just like this. Arrows also cannot be used with new, because they have no [[Construct]] behavior and no prototype property.
function outer() {
const arrow = () => arguments[0];
return arrow('ignored');
}
console.log(outer('from outer')); // 'from outer'
const Make = () => {};
try {
new Make();
} catch (e) {
console.log(e instanceof TypeError); // true
}Inside arrows, use rest parameters ((...args) => args) instead of arguments.
Arrow Functions as Class Fields
A common pattern for event handlers is an arrow function assigned to a class field. The field initializer runs inside the constructor, so the arrow captures the instance's this. The method then keeps working when it is detached from the object.
class Button {
constructor(label) {
this.label = label;
}
handleClick = () => `${this.label} clicked`;
describe() {
return `Button: ${this.label}`;
}
}
const save = new Button('Save');
const { handleClick, describe } = save;
console.log(handleClick()); // 'Save clicked'
try {
describe(); // class bodies are strict, so this is undefined
} catch (e) {
console.log(e.constructor.name); // 'TypeError'
}This convenience has a cost. Each instance gets its own copy of the handleClick closure, while describe lives once on Button.prototype.
| Approach | Where the function lives | Survives detaching | Overridable via subclass and `super` | Per-instance memory |
|---|---|---|---|---|
| Prototype method | `Class.prototype`, shared | No | Yes | None |
| Arrow class field | Each instance | Yes | Not through `super.method()` | One closure per instance |
| `this.m = this.m.bind(this)` in constructor | Each instance (bound copy) | Yes | Yes, prototype method still exists | One bound function per instance |
For a few hundred UI components the per-instance cost doesn't matter. For hundreds of thousands of small objects, prefer prototype methods and bind only where a callback is actually detached.
Choosing Between Them
| Situation | Use | Reason |
|---|---|---|
| Object literal or class method | Method shorthand | `this` should be the receiver |
| Callback to `setTimeout`, `map`, `then` inside a method | Arrow | Keeps the method's `this` |
| Library sets `this` for the callback (Mocha, some DOM APIs) | Regular function | The arrow would ignore the provided `this` |
| Constructor or anything called with `new` | Regular function or class | Arrows cannot be constructed |
| Handler passed around detached from its object | Arrow class field or `bind` | `this` is fixed in advance |
Exercise
In strict mode, what does obj.run() return, and why? Code: const obj = { n: 5, run() { return [1, 2].map(function (x) { return x * this.n; }); } };
Show answer
It throws a TypeError. map calls the callback as a plain function and no thisArg is passed, so this inside the callback is undefined, and reading this.n fails. You can fix it with an arrow callback (x => x * this.n), which takes this from run, or by passing this as the second argument to map. The result is then [5, 10].
Exercise
A teammate writes const counter = { count: 0, inc: () => { this.count += 1; } }; and then counter.inc() does not change counter.count. Explain what happens and give a fix.
Show answer
The object literal does not create a scope, so the arrow's this comes from the surrounding code (module.exports in CommonJS, or undefined in an ES module, where the call throws). counter.count is never touched. Use method shorthand instead: inc() { this.count += 1; }.
Exercise
Why does arrow.bind(target)() still return the original lexical this instead of target?
Show answer
An arrow function has no this binding of its own. Its this is resolved through the enclosing scope when the arrow is created, like a captured variable. bind, call, and apply can only set the this binding of functions that have one, so the value they pass is ignored.