
this Depends on How a Function Is Called, Not Where It's Written
- كاتب موثّق
- ES2025
محتويات المقال
egp.format(120) works fine in the console, so a developer writes prices.map(egp.format) to format the whole list, and Chrome throws TypeError: Cannot read properties of undefined (reading 'currency'). The method is defined in the PriceFormatter class, currency is set in the constructor, and the instance clearly exists. So how can this be undefined?
The common misconception
this inside a method refers to the object the method belongs to, the class or object literal you wrote it in. Hand the method to someone else and it still knows its owner.
egp.format(...), and then this really is egp. Other languages reinforce it: a C# delegate or a Java method reference created from an instance method keeps its instance. And , which really do care about where they're written, blur the picture further. But in JavaScript, a regular function's this isn't attached to the function at all. It arrives with each call.
What actually happens
this is a hidden argument filled in at call time
this as a hidden parameter: like the parameters you declare, it's a binding the language creates when the function runs. For a regular function, its value is the object the function was accessed on. In egp.format(120), that's egp, the object before the dot.
format is one function object living on PriceFormatter.prototype, shared by every instance. Reading egp.format without calling it just gives you that function; it doesn't create a version tied to egp. That's also why the bug only appears once the method leaves home: as long as every call is written egp.format(...), the belief and the real rule give the same answer.
Why map gets undefined
prices.map(egp.format) hands map the bare function. map then calls it as a plain callback with no object before the dot, and since no thisArg was passed, this is undefined. Class bodies always run in , so this stays undefined and reading this.currency throws. In an old non-strict script, the same call would quietly set this to globalThis, and you'd get "120.00 undefined" instead of an error, which is worse.
class PriceFormatter { constructor(currency) { this.currency = currency; } format(amount) { return `${amount.toFixed(2)} ${this.currency}`; }}const egp = new PriceFormatter("EGP");console.log(egp.format(120)); // 120.00 EGPconsole.log([120, 80].map(egp.format));// TypeError: Cannot read properties of undefined (reading 'currency')class PriceFormatter { constructor(currency) { this.currency = currency; } format(amount) { return `${amount.toFixed(2)} ${this.currency}`; }}const egp = new PriceFormatter("EGP");// call it as a method inside an arrow function...console.log([120, 80].map((amount) => egp.format(amount)));// ...or pass a bound copy whose this is fixedconsole.log([120, 80].map(egp.format.bind(egp)));// both print [ '120.00 EGP', '80.00 EGP' ]egp.format(amount) with egp before the dot, every time. The second version passes a : bind returns a new function that always calls format with this set to egp.
One function, many receivers
this comes from the call, the same function can see a different object on every line. Copying a method to another object, extracting it into a variable, or calling it with call all change this, while bind locks it:
"use strict";function describe() { return this === undefined ? "no this" : this.name;}const cart = { name: "cart", describe };const wishlist = { name: "wishlist", describe: cart.describe };console.log(cart.describe()); // cartconsole.log(wishlist.describe()); // wishlist: same function, new receiverconst detached = cart.describe;console.log(detached()); // no this: nothing before the dotconsole.log(describe.call({ name: "order" })); // orderconst bound = describe.bind(cart);console.log(bound.call(wishlist)); // cart: bind beats callconsole.log(bound.bind(wishlist)()); // cart: you can't re-bindnew Fn() is one more call form: it creates a fresh object and passes it as this.
Arrow functions are the exception
this of its own. It reads this from the code around it, as it was when the arrow was created, and call, apply and bind can't change it. That's exactly why (amount) => egp.format(amount) is safe, and why an arrow defined inside a method keeps the method's this in a setTimeout callback.
{ total: 0, add: () => this.total++ }, the braces aren't a function, so the arrow takes this from the code around the literal, not from the object. Here is the whole rule in one table:
this is | |
|---|---|
obj.method() | obj, the object before the dot at call time |
fn(), including callbacks called this way | undefined in strict code; globalThis in old non-strict scripts |
fn.call(x) or fn.apply(x) | x |
fn.bind(x), then the result is called | x, permanently; call or another bind can't change it |
this of the surrounding code when the arrow was created | |
el.addEventListener("click", fn) | fn came from |
How to apply it in your project
Search for detached methods Look for .map(obj.method),setTimeout(this.method),addEventListener("…", this.method)and destructured methods likeconst { format } = egp. Each one passes a function without its receiver.Fix it at the call site Wrap the call in an arrow, (x) => obj.method(x), or passobj.method.bind(obj). For array methods,thisArgworks too.Use arrow class fields for handlers that travel For a method that's always passed around, like a click handler, a class field such as onClick = () => { … }binds to the instance. Each instance gets its own copy of the function, so keep regular methods for everything else.Keep code in strict mode ES modules and classes are strict by default. There, a lost thisthrows right away instead of silently readingglobalThis, so the bug is loud the first time it runs instead of quietly producingundefinedvalues.
Key takeaways
thisis decided at call time by how the function is called, not by where the method is written.obj.method()passesobj; a bare call passesundefinedin strict code, which includes classes and modules.Passing obj.methodas a callback hands over the function alone, and the receiver is lost.bindfixesthispermanently, while arrow functions have nothisof their own and use the surrounding one.Fix a lost receiver at the call site with an arrow wrapper, bindor athisArg.
التعليقات (0)