Sub topic 4
Method Calls and the Object Before the Dot
The previous chapter covered plain function calls such as f(), where no object is involved and this falls back to undefined or the global object. Most real code calls functions as methods, as in user.save() or list.push(x). This chapter explains the rule for those calls, which is called implicit binding. It also covers the edge cases that decide whether a call counts as a method call at all.
This chapter assumes you know how to write object literals, method shorthand syntax, and basic prototypes with Object.create. It also assumes you have read the earlier chapters on call sites and default binding. Examples run in strict mode unless noted, because modules and classes are strict by default.
The rule in one sentence
When a function is called through a property access, this is the object the property was read from: the value to the left of the last . or [...] just before the call parentheses.
'use strict';
function describe() {
return `${this.name} has ${this.legs} legs`;
}
const dog = { name: 'Rex', legs: 4, describe };
const bird = { name: 'Tweety', legs: 2, describe };
console.log(dog.describe()); // 'Rex has 4 legs'
console.log(bird.describe()); // 'Tweety has 2 legs'Only one function object exists here. Neither dog nor bird owns it in any special sense. Both just hold a reference to it in a property. The value of this comes from the expression used at the call site, so the same function sees a different this on each call.
How the engine sees a method call
The specification describes dog.describe as producing a Reference. A Reference is an internal record that holds two things: a base value (dog) and a property name ('describe'). When the call operator () is applied to a Reference whose base is an object (or a primitive), the engine:
- Looks up the property on the base value, including the prototype chain, to get the function.
- Calls that function with the base value as
this.
When the thing before () is not a property Reference, for example a plain variable or the result of some other expression, step 2 has no base to use, and default binding applies instead.
This model explains every case in the rest of the chapter. Each time, the question is whether the call still has a base value at the moment it happens.
Only the last link in the chain counts
With nested objects, this is the object immediately before the final property, not the outermost one.
'use strict';
const app = {
name: 'app',
settings: {
name: 'settings',
whoAmI() {
return this.name;
}
}
};
console.log(app.settings.whoAmI()); // 'settings'The engine first evaluates app.settings to an ordinary object value. Then .whoAmI builds a Reference whose base is that inner object. app plays no part in the call. A common mistake is to expect this to be the "top" object in a namespace, such as config.db.connect() reaching config. It reaches config.db.
Bracket notation and arrays
Computed property access works the same way as the dot.
'use strict';
const actions = {
label: 'actions',
run() {
return this.label;
}
};
const key = 'run';
console.log(actions[key]()); // 'actions'
const handlers = [
function () {
return this.length;
}
];
console.log(handlers[0]()); // 1, this is the array itselfThe second example catches people out. Calling a function stored in an array passes the array as this, because handlers[0] is a property access with handlers as its base. It rarely causes bugs, but it can surprise you when you inspect this inside a dispatch table.
Methods found on the prototype
The property lookup can walk the prototype chain, but this does not follow it. this is always the object you started the lookup from, known as the receiver, and never the object where the function was found.
'use strict';
const animal = {
speak() {
return `${this.name} makes a sound`;
}
};
const cat = Object.create(animal);
cat.name = 'Tom';
console.log(Object.hasOwn(cat, 'speak')); // false
console.log(cat.speak()); // 'Tom makes a sound'
console.log(animal.speak()); // 'undefined makes a sound'This behavior is what makes prototype-based sharing work. One speak function on animal serves every object created from it, and each call reads data from whichever object received the call. Built-in methods rely on the same mechanism. [1, 2].push(3) finds push on Array.prototype and runs it with your array as this.
Getters and setters
Accessor properties follow the same rule even though no call parentheses appear in the source. Reading or writing the property calls the getter or setter with the receiver as this.
'use strict';
const thermometer = {
celsius: 20,
get fahrenheit() {
return this.celsius * 9 / 5 + 32;
},
set fahrenheit(f) {
this.celsius = (f - 32) * 5 / 9;
}
};
console.log(thermometer.fahrenheit); // 68
thermometer.fahrenheit = 212;
console.log(thermometer.celsius); // 100
const kitchen = Object.create(thermometer);
kitchen.celsius = 5;
console.log(kitchen.fahrenheit); // 41, getter runs with kitchen as thisWhen the setter runs through kitchen, it writes this.celsius onto kitchen and leaves thermometer alone. The inherited getter therefore behaves per instance with no extra code.
Which syntax still counts as a method call
Optional chaining and grouping parentheses keep the base value. Expressions that produce a new value drop it.
'use strict';
const obj = {
check() {
return this === obj;
}
};
console.log(obj.check()); // true
console.log(obj?.check()); // true, optional chaining keeps the base
console.log(obj.check?.()); // true
console.log((obj.check)()); // true, grouping parentheses keep the Reference
const loose = (0, obj.check);
console.log(typeof loose); // 'function'
console.log((0, obj.check)() === undefined || obj.check.call(undefined)); // see belowThat last line hides the actual behavior, so here is the same case with the answer shown directly:
'use strict';
const obj = {
peek() {
return this;
}
};
console.log((obj.peek)() === obj); // true
console.log((0, obj.peek)()); // undefined, comma operator produced a plain value
console.log((obj.peek = obj.peek)()); // undefined, assignment produced a plain value
console.log((true && obj.peek)()); // undefined, logical operator produced a plain valueThe grouping operator ( ) hands back the Reference unchanged, so (obj.peek)() is still a method call. The comma, assignment, &&, ||, and ?? operators all evaluate their operand down to a plain function value, so the base is gone. Bundlers and transpilers sometimes emit (0, obj.fn)() for exactly this reason: they want a call with no this.
The next chapter covers the most common way to lose the base: assigning a method to a variable or passing it as a callback.
Primitives as the base
You can call methods on strings, numbers, and booleans, so a primitive can be the base value. In strict mode the function receives the primitive itself as this. In sloppy mode it receives a wrapper object.
function strictKind() {
'use strict';
return typeof this;
}
function sloppyKind() {
return typeof this;
}
Object.defineProperty(String.prototype, 'strictKind', { value: strictKind, configurable: true });
Object.defineProperty(String.prototype, 'sloppyKind', { value: sloppyKind, configurable: true });
console.log('hi'.strictKind()); // 'string'
console.log('hi'.sloppyKind()); // 'object', a String wrapper
delete String.prototype.strictKind;
delete String.prototype.sloppyKind;This example only demonstrates the difference. Avoid adding properties to built-in prototypes in real code. Built-in methods such as 'abc'.toUpperCase() use the same path: the string is the base, and the method reads it through this.
Method shorthand vs function-valued properties
All three of the following give you implicit binding when called as obj.x():
'use strict';
const viaShorthand = {
tag: 'shorthand',
show() { return this.tag; }
};
const viaExpression = {
tag: 'expression',
show: function () { return this.tag; }
};
const viaArrow = {
tag: 'arrow',
show: () => typeof this
};
console.log(viaShorthand.show()); // 'shorthand'
console.log(viaExpression.show()); // 'expression'
console.log(viaArrow.show()); // 'undefined' in a module or strict function scopeShorthand methods and function expressions behave the same way with respect to this. Shorthand methods differ in two ways: they cannot be used with new, and they can use super. Arrow functions ignore implicit binding entirely, because they never receive a this of their own. They are covered in a later chapter. For now, remember that an arrow function stored as an object property is almost never what you want when it needs to read the object.
Common errors
| Symptom | Cause | Fix | Column | Column |
|---|---|---|---|---|
| `this` is an inner object, not the namespace you expected | Only the object before the final accessor is the base | Call through the object you mean, or reference the outer object by name | ||
| `this.x` reads `undefined` on a prototype method | Called on the prototype itself, e.g. `Proto.method()` | Call through an instance that holds the data | ||
| `this` is undefined after `(a, obj.f)()` or `(obj.f | g)()` | The operator dropped the Reference | Call `obj.f()` directly, or use `call` (next chapters) | |
| Arrow-valued property returns the wrong `this` | Arrow functions skip implicit binding | Use method shorthand | ||
| Inherited setter changes the wrong object | Expecting the setter to write to the prototype | `this` is the receiver. Write to the prototype explicitly if shared state is intended |
Summary
- Implicit binding: in
base.fn()orbase[key](),thisisbase. - Only the last accessor before the call matters. Outer objects in a chain are ignored.
- Prototype lookup finds the function, but
thisstays the receiver. Getters and setters follow the same rule. - Grouping parentheses and optional chaining keep the base. Comma, assignment, and logical operators drop it.
- Arrow functions do not take part in implicit binding.
Exercise
Given const shop = { name: 'shop', cart: { name: 'cart', total() { return this.name; } } };, what do shop.cart.total(), (shop.cart.total)(), and (shop.cart.total || null)() return in strict mode?
Show answer
'cart', 'cart', and a TypeError. The first two are method calls whose base is shop.cart, because grouping parentheses keep the Reference. In the third, || evaluates to a plain function value, so this is undefined and reading this.name throws a TypeError.
Exercise
const base = { get id() { return this.key; } }; const child = Object.create(base); child.key = 7; What is child.id, and what is base.id? Explain why.
Show answer
child.id is 7 and base.id is undefined. The getter is found on base in both cases, but it runs with the receiver as this. Reading through child makes this equal to child, which has key set to 7. Reading through base makes this equal to base, which has no key property.
Exercise
A teammate writes const api = { url: '/v1', fetchAll: () => fetch(this.url) }; and finds that api.fetchAll() requests the wrong URL. Why does the call api.fetchAll() not set this to api, and what is the smallest fix?
Show answer
fetchAll is an arrow function, and arrow functions have no this of their own, so implicit binding does not apply. They use the this of the surrounding scope, which is undefined at module level. The smallest fix is method shorthand: fetchAll() { return fetch(this.url); }.