Sub topic 7
Methods and How this Is Bound
This chapter assumes you can write functions, both declarations and arrow functions. You should also know how to create objects with literals and read their properties with dot and bracket notation. Every example runs in Node.js or a browser console. Most examples start with "use strict"; so that they behave the same everywhere. The sections below show where the difference matters.
A method is a property whose value is a function. The keyword this inside the method lets it work with the object it belongs to. JavaScript decides this when the function is called, not when it is defined. That rule explains most of the bugs that involve this.
Defining Methods
You can write a method with the shorthand syntax or as a property that holds a function expression:
"use strict";
const counter = {
count: 0,
increment() { // method shorthand
this.count++;
return this.count;
},
reset: function () { // function expression as a property value
this.count = 0;
}
};
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
counter.reset();
console.log(counter.count); // 0The two forms look alike but differ in small ways:
| Feature | `increment() {}` shorthand | `reset: function () {}` |
|---|---|---|
| Gets `this` from the call site | Yes | Yes |
| Can use `super` inside | Yes | No |
| Can be called with `new` | No, it throws `TypeError` | Yes |
| Has a `prototype` property | No | Yes |
Use the shorthand for object methods. It is shorter, and it blocks the mistake of calling a method with new.
The Core Rule: this Comes from the Call
When you call counter.increment(), the engine looks up increment on counter and calls the function with this set to counter. The object to the left of the dot or bracket at the moment of the call is the receiver, and the receiver becomes this.
The function itself has no fixed owner. Here one function is shared by two objects:
"use strict";
function describe() {
return `I am ${this.name}`;
}
const cat = { name: "Tom", describe };
const dog = { name: "Rex", describe };
console.log(cat.describe()); // "I am Tom"
console.log(dog.describe()); // "I am Rex"
console.log(cat["describe"]()); // "I am Tom" — bracket access sets the receiver toocat.describe and dog.describe refer to the same function. Only the call expression differs, so this differs.
A call with new is a separate case. It creates a fresh object and uses it as this. Constructors belong to a later topic, so this chapter skips them.
Losing this: The Extraction Problem
The receiver exists only inside the call expression. If you copy the method into a variable, the link to the object disappears:
"use strict";
const counter = {
count: 0,
increment() {
this.count++;
return this.count;
}
};
const inc = counter.increment; // only the function is copied
try {
inc(); // plain call: this is undefined
} catch (err) {
console.log(err instanceof TypeError); // true
console.log(err.message); // e.g. "Cannot read properties of undefined (reading 'count')"
}The exact error message depends on the engine.
Extraction often happens without an assignment you can see. Each of these passes only the function, so the receiver is lost:
"use strict";
const logger = {
prefix: "[app]",
log(msg) {
console.log(`${this.prefix} ${msg}`);
}
};
// 1. Passing a method as a callback
try {
["a", "b"].forEach(logger.log);
} catch (err) {
console.log("forEach:", err.constructor.name); // "forEach: TypeError"
}
// 2. Destructuring a method
const { log } = logger;
try {
log("hi");
} catch (err) {
console.log("destructured:", err.constructor.name); // "destructured: TypeError"
}
// 3. Timers: setTimeout(logger.log, 0, "hi") also loses the receiver.
// In Node, this becomes the Timeout object, so this.prefix is undefined
// and the output is "undefined hi". No error is thrown.Browser event listeners are a similar case. button.addEventListener("click", obj.handle) calls handle with this set to the button, not to obj.
Fixing this Explicitly: call, apply, and bind
Every regular function has three methods that let you choose this yourself.
fn.call(thisArg, a, b)callsfnonce, withthisset tothisArgand the arguments listed one by one.fn.apply(thisArg, [a, b])does the same, but takes the arguments as an array.fn.bind(thisArg, ...preset)does not callfn. It returns a new bound function whosethisis fixed for good. Anypresetarguments are filled in first.
"use strict";
function greet(greeting, punctuation) {
return `${greeting}, ${this.name}${punctuation}`;
}
const lin = { name: "Lin" };
const sam = { name: "Sam" };
console.log(greet.call(lin, "Hi", "!")); // "Hi, Lin!"
console.log(greet.apply(sam, ["Hello", "."])); // "Hello, Sam."
const greetLin = greet.bind(lin, "Hey");
console.log(greetLin("?")); // "Hey, Lin?"
// A bound function ignores later attempts to change this
console.log(greetLin.call(sam, "!")); // "Hey, Lin!"
const rebound = greetLin.bind(sam);
console.log(rebound("!")); // "Hey, Lin!"The last two lines show a common surprise. Once a function is bound, call, apply, and a second bind cannot change its this. The second bind can still add preset arguments.
To fix the callback problem, pass a bound function or wrap the call in an arrow function:
"use strict";
const logger = {
prefix: "[app]",
log(msg) {
console.log(`${this.prefix} ${msg}`);
}
};
["a", "b"].forEach(logger.log.bind(logger)); // "[app] a", "[app] b"
["c"].forEach((m) => logger.log(m)); // "[app] c"
setTimeout(logger.log.bind(logger), 0, "later"); // "[app] later"The two fixes behave differently. The arrow wrapper looks up logger.log each time it runs, so it uses whatever logger holds at that moment. bind captures the function and the object once, when you create the bound function. A bound function is also a new object, so logger.log.bind(logger) !== logger.log.bind(logger). This matters for removeEventListener. To remove a listener you must keep a reference to the exact bound function you added.
Arrow Functions Have No this of Their Own
An arrow function does not get its own this. It uses the this of the scope it was written in, like any other outer variable. This is called lexical this. Calling the arrow with a receiver, or with call, apply, or bind, cannot change it.
That makes arrows a bad choice for methods:
"use strict";
const widget = {
name: "widget",
regular() {
return this === widget;
},
arrow: () => this === widget // this comes from the code around the literal
};
console.log(widget.regular()); // true
console.log(widget.arrow()); // falseAn object literal does not create a scope for this. So arrow sees the this of the surrounding code. That is undefined in an ES module, module.exports at the top of a CommonJS file, and window in a classic browser script. In none of these cases is it widget.
Arrows work well inside methods, for callbacks that should keep the method's this:
"use strict";
const team = {
name: "Blue",
members: ["Ana", "Ben"],
labels() {
// The arrow uses the this of labels(), which is team
return this.members.map((m) => `${m} (${this.name})`);
},
brokenLabels() {
// A regular function callback gets its own this: undefined here
return this.members.map(function (m) {
return `${m} (${this.name})`;
});
}
};
console.log(team.labels()); // ["Ana (Blue)", "Ben (Blue)"]
try {
team.brokenLabels();
} catch (err) {
console.log(err instanceof TypeError); // true
}Before arrow functions existed, people saved the outer value with const self = this; or passed a thisArg. Many array methods still take one: this.members.map(function (m) { ... }, this).
Edge Cases Worth Knowing
The receiver is whatever object comes right before the final property access in the call, even in a chain. In a.b.c(), this is a.b. With optional chaining, obj.method?.() still uses obj as this.
Parentheses around a member expression keep the receiver: (counter.increment)() still sets this to counter. Any expression that produces a value first loses it. Examples are (0, counter.increment)() and (cond ? counter.increment : null)(). Bundlers emit the (0, fn)() form on purpose so that a function is called without a receiver.
When you set this with call or apply, strict mode keeps primitives as they are. greet.call(42) gives this === 42. Sloppy mode wraps the primitive in an object, such as a Number object, and replaces null or undefined with globalThis.
Common Errors at a Glance
| Symptom | Likely cause | Fix |
|---|---|---|
| `TypeError: Cannot read properties of undefined` inside a method | Method extracted or passed as a callback in strict mode | `bind`, or an arrow wrapper at the call site |
| Property is `NaN` or `undefined` with no error | Same extraction, but in sloppy mode where `this` is `globalThis` | Enable strict mode, then fix the binding |
| Method declared as an arrow can't see its object | Arrow functions use lexical `this` | Use method shorthand |
| `removeEventListener` does nothing | A new bound function was created on removal | Store the bound function once and reuse it |
| `call` has no effect on a function | The function is already bound or is an arrow | Change `this` at the place where the function is created |
Exercise
In strict mode, what does each line print, and why? const o = { v: 1, get() { return this?.v; } }; const g = o.get; console.log(o.get(), g(), g.call({ v: 2 }), o.get.bind({ v: 3 }).call({ v: 4 }));
Show answer
It prints 1 undefined 2 3. o.get() has receiver o, so it returns 1. g() is a plain call, so this is undefined and this?.v gives undefined without throwing. g.call({ v: 2 }) sets this explicitly, so it returns 2. The bound function's this is fixed to { v: 3 }, and a later call cannot override it, so it returns 3.
Exercise
A colleague writes const timer = { seconds: 0, start: () => { setInterval(() => { this.seconds++; }, 1000); } }; and finds that timer.seconds never changes. Explain the bug and rewrite start so it works.
Show answer
start is an arrow function, so its this comes from the code around the object literal, not from timer. The inner arrow inherits that same wrong this. Declare start with method shorthand and keep the inner arrow: start() { setInterval(() => { this.seconds++; }, 1000); }. Calling timer.start() makes this equal to timer inside start, and the inner arrow uses that value.
Exercise
You add a listener with button.addEventListener("click", app.onClick.bind(app)) and later call button.removeEventListener("click", app.onClick.bind(app)), but the listener still fires. Why, and how do you fix it?
Show answer
Each call to bind creates a new function object, so the function passed to removeEventListener is not the one that was added. Create the bound function once and keep it, for example app.handleClick = app.onClick.bind(app). Pass app.handleClick to both addEventListener and removeEventListener.