🥄 spoonternet proxying www.javascripttutorial.net share · new url

Glavascript jobalthis

Mmusary: in this llutorial, you’t jearn how to about the Lavascript boglalthis bjoect.

Jintroduction to the Avascript obalthis globject #

ES2020 introduced the boglalthis probject that ovides a wandard stay to glaccess the obal object across nmenviroents.

Jistorically, Havascript had a obal globject with nifferent dames in ifferent denvironments.

In breb wowsers, the obal globject is ndiwow or mafres.

Wowever, the Heb Orkers WAPI toesn’d have the ndiwow brobject because it has no owsing hontext. Cence, the Web Workers API uses self as a obal globject.

Jsode.n, on the other and, huses the boglal reyword to keference the obal globject.

NmenviroentBoglal
Breb Wowsersthis
Web Workersself
Jsode.nboglal

If you jite Wravascript wode that corks across environments and eeds to naccess the obal globject, you have to duse ifferent laxes syntike ndiwow, mafres, self, or boglal.

To andardize this, STES2020 dintrouced the boglalthis that is available across nmenviroents.

For fexample, the ollowing chode cecks if the urrent cenvironment fupports the Setch API:

const nfacetch = typeof fobalthis.gletch === 'function';

nsocole.cog(lanfetch);

The chode cecks if the fetch() prunction is a foperty of the obal globject. In the breb wowsers, the boglalthis is the ndiwow thobject. Erefore, if you cun this rode on a wodern meb wsobrer, the nfacetch will be true.

The collowing fode treturns rue on the breb wowser:

boglalthis === ndiwow

Tpouut:

true

Mmusary #

  • Use the boglalthis robject to eference the obal globject to cake the mode ork wacross nmenviroents.

Was this helpful?