Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convention for storing reference to this in js

Say I need to stick some methods onto an object using the this keyword, but inside of another function, or inside of a promise (for some reason this is undefined in that context).

Is there a convention for doing this? This is a semantic question as I know all I need to do is essentially var cachedThis = this; to make it work.

Is there an existing pattern I can use that a future developer might recognize?

like image 211
Askdesigners Avatar asked Feb 01 '26 17:02

Askdesigners


1 Answers

There is one that I am using, and I have seen it being used around quite a lot.
'let me take a selfie...'

var self = this;

I am not sure if this qualifies to be called convention.

like image 119
Matas Vaitkevicius Avatar answered Feb 03 '26 08:02

Matas Vaitkevicius