الانتقال إلى المحتوى
FrontendJavaScript· 7 دقائق للقراءة

this Depends on How a Function Is Called, Not Where It's Written

A method doesn't remember its object. The call site passes this in, every single time.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • ES2025
محتويات المقال

A pricing page formats a list of totals. 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

The belief: 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.

It's an easy belief to pick up, because most of the time it holds. You usually call methods as 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

MDN suggests thinking of 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.

The function itself stores no owner. 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.

JavaScript prices.js
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')

The arrow version works because the arrow's body calls 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

Because 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:

JavaScript receivers.js
"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-bind

The same rule covers inheritance: a method found on a prototype still gets the object you called it on, not the prototype that holds it. And new Fn() is one more call form: it creates a fresh object and passes it as this.

Arrow functions are the exception

An arrow function doesn't get a 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.

The flip side: arrows make poor object-literal methods. In { 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:

How the function is calledWhat this is
obj.method()obj, the object before the dot at call time
fn(), including callbacks called this wayundefined in strict code; globalThis in old non-strict scripts
fn.call(x) or fn.apply(x)x
fn.bind(x), then the result is calledx, permanently; call or another bind can't change it
An arrow function, called any wayThe this of the surrounding code when the arrow was created
el.addEventListener("click", fn)The element the listener is on, not the object fn came from

How to apply it in your project

  1. Search for detached methodsLook for .map(obj.method), setTimeout(this.method), addEventListener("…", this.method) and destructured methods like const { format } = egp. Each one passes a function without its receiver.
  2. Fix it at the call siteWrap the call in an arrow, (x) => obj.method(x), or pass obj.method.bind(obj). For array methods, thisArg works too.
  3. Use arrow class fields for handlers that travelFor 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.
  4. Keep code in strict modeES modules and classes are strict by default. There, a lost this throws right away instead of silently reading globalThis, so the bug is loud the first time it runs instead of quietly producing undefined values.

Key takeaways

  • this is decided at call time by how the function is called, not by where the method is written.
  • obj.method() passes obj; a bare call passes undefined in strict code, which includes classes and modules.
  • Passing obj.method as a callback hands over the function alone, and the receiver is lost.
  • bind fixes this permanently, while arrow functions have no this of their own and use the surrounding one.
  • Fix a lost receiver at the call site with an arrow wrapper, bind or a thisArg.

📚 المصادر

  1. this — MDN
  2. Arrow function expressions — MDN
  3. Function.prototype.bind() — MDN
  4. Strict mode — MDN
  5. EventTarget: removeEventListener() method — MDN

التعليقات (0)