0

how to initialize private properties within a event handler?

So I have a class whose constructor contains a window.onresize event handler that needs to initialize the class's private properties. The problem is that the 'this' keyword within the window.onresize event handler refers to the window object and not to my class. https://code.sololearn.com/WIf2vu9FZF7O

9th Nov 2021, 5:29 PM
Moshe Schnitzler
Moshe Schnitzler - avatar
1 Respuesta
+ 2
The `this` variable changes based on which scope it's currently in. Since the callback of window resize event is run asynchronously, it will run at a later time when `this` has changed scope I believe... The way around this is to store the instance of `this` in a variable before the callback, then use that reference to change the values of the "`this`" object like you intended. Similar answer from stack overflow: https://stackoverflow.com/questions/3076010/accessing-class-member-variables-inside-an-event-handler-in-javascript https://code.sololearn.com/WzmsA8rdPX1n/?ref=app
10th Nov 2021, 4:59 AM
EricMcDerrick
EricMcDerrick - avatar