[Javascript] addEventListener and this keyword

      No Comments on [Javascript] addEventListener and this keyword

Recently I was writing some script when I bumped into a problem with this in javascript. I wanted execute function once the user select the file to be processed.

And then the Controller, simulating class used this keyword

However calling doSomething was resulting in error
14:24:23.401 TypeError: this.doSomething is not a function

The reason for that is that when function OnNewFilesAdded is called, the this context was setted up as I originally expected. The this keyword doesn’t reference the object in which it’s declared, but the object which called this function.

Solution to this problem is to use .bind(obj) method to manually set the context / object referenced by this.

After changing the addEventListener to following

So using the bind method we explicitly said that the this execution context should have the value of Controller instead of the object returned by getElementById(‘files’) as the executor of OnNewFilesAdded.

One more simple demonstration of this concept can be seen in this example :

Which then prints


Hello(): this contex properties myprop,thisMyClass,Hello
Proxy.Call(), this context properties : reference,thisIsProxy,call
Hello(): this contex properties reference,thisIsProxy,call

When we are calling obj.Hello() we can see this is referencing the object of MyClass as expected.
However, in second case the call to Hello() function is indirect through proxy object. And because the function obj.Hello() is called from Proxy object, it’s context is preserved also inside the call of Hello() function.

If we would want to fix this problem, again, we can use .bind method. Change the original

to

and now the output of the script will be


Hello(): this contex properties myprop,thisMyClass,Hello
Proxy.Call(), this context properties : reference,thisIsProxy,call
Hello(): this contex properties myprop,thisMyClass,Hello

Here as we can see, the this in second call is correctly (assuming this is the functionality we wanted) referencing the MyClass object, instead of Proxy object.

Leave a Reply

Your email address will not be published. Required fields are marked *