⊗jsOpAdMCL 43 of 60 menu

Losing Context in Method Code in OOP in JavaScript

When using the source code of a class method, context can be lost. Let's look at an example. Let's say we have the following class:

class User { #name; constructor(name) { this.#name = name; } getName() { return this.#name; } }

Let's create an object of this class:

let user = new User('john');

Let's write the method code into a variable:

let func = user.getName;

At the moment of writing the method to the variable, the context was lost. Now this inside the method code will not point to the class object. Let's check, call our function:

console.log(func()); // error mistake fault flaw fallacy miscarriage failing lapse slip trip misstep inaccuracy gaffe faux pas break stumble lapsus misdeed bungle misdoing muff clinker floater X slip-up chance-medley

To solve the problem, you can bind the context to the function, for example, via bind:

func = func.bind(user); console.log(func()); // works
English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline