Sub topic 7
Methods and How this Is Bound
This chapter assumes you can write functions, create object literals, and read properties with dot and bracket notation. It covers how methods are defined, how this gets its value, and how to keep that value when you pass a method around.
Defining Methods
A method is a property whose value is a function. Method shorthand is the usual way to write one inside an object literal:
const user = {
name: "Lin",
greet() {
return `Hi, I'm ${this.name}`;
},
};
console.log(user.greet()); // "Hi, I'm Lin"greet() { ... } does about the same thing as greet: function () { ... }. Inside the method, this refers to the object the method was called on.
this Is Set by the Call, Not the Definition
The most important rule is that a regular function gets this when it is called, not when it is written. JavaScript looks at the call expression:
obj.method()setsthistoobj, the object before the dot.method()with no object givesundefinedin strict mode. In sloppy (non-strict) scripts it gives the global object.method.call(obj, ...args)andmethod.apply(obj, args)setthistoobjfor that one call.- A function returned by
method.bind(obj)always usesobjasthis.
Losing this When Extracting a Method
A common error is to copy a method into a variable, or pass it as a callback, and then call it on its own. The function no longer remembers its object.
"use strict";
const counter = {
count: 0,
increment() {
this.count++;
return this.count;
},
};
console.log(counter.increment()); // 1
const loose = counter.increment;
try {
loose(); // this is undefined, so this.count throws
} catch (err) {
console.log(err instanceof TypeError); // true
}
const bound = counter.increment.bind(counter);
console.log(bound()); // 2The same thing happens with setTimeout(counter.increment, 100) or button.addEventListener("click", counter.increment). In those calls you pass the function itself, so the object before the dot is lost. You can fix it with bind, or wrap the call in an arrow function: () => counter.increment().
Arrow Functions and this
Arrow functions have no this of their own. They use the this of the code around them. That makes them a poor choice for methods and a good choice for callbacks inside methods:
const team = {
name: "Core",
members: ["Ada", "Lin"],
list() {
return this.members.map((m) => `${m} (${this.name})`);
},
};
console.log(team.list()); // ["Ada (Core)", "Lin (Core)"]The arrow function inside map uses the this that list received. If you replaced it with a regular function (m) { ... }, it would get its own this, which is undefined in strict mode, and this.name would throw.
The reverse mistake is writing a method as an arrow function, as in greet: () => this.name. In that case this comes from the scope around the object literal, not from the object, so greet never sees name.
| Form | Own `this`? | Good as a method? |
|---|---|---|
| `greet() {}` | Yes, set by the call | Yes |
| `greet: function () {}` | Yes, set by the call | Yes |
| `greet: () => {}` | No, uses the outer scope | No |
Exercise
Given const dog = { sound: "woof", speak() { return this.sound; } }; in strict mode, what happens with const s = dog.speak; s();, and give two ways to make it return "woof".
Show answer
The call throws a TypeError, because s() has no object before the dot, so this is undefined. Fixes: const s = dog.speak.bind(dog); s(); or call it through a wrapper such as const s = () => dog.speak(); s();. Calling s.call(dog) also works for a single call.
Exercise
Why does const o = { n: 1, get: () => this.n }; fail to return 1 from o.get()?
Show answer
Arrow functions take this from the scope around them, not from the call. Here this comes from the scope that contains the object literal, not from o, so this.n does not read o.n. Use method shorthand: get() { return this.n; }.