Over a million developers have joined DZone.

Typescript, jQuery and the ‘this’ context causing issues

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

Today I was in the middle of porting some raw javascript over to TypeScript as well as moving inline javascript into separate classes.  In the middle of doing this I started to run into some really odd stuff.  Namely, the ‘this’ context in one of my methods was set to window, not to the parent object.  This was really weird and at first I thought maybe it had to do w/ Inheritance and Typescript (this class implemented a base class).  Sadly even when I removed the base class I was still getting the results.

After a bunch of digging I was able to find the root cause, Derik was doing something stupid and jQuery was making it worse :)

In order to get some feedback and to help illustrate my issue.

Here is what my Typescript class which was having the issue looked like.  The box in red is what was throwing the error.


From Chrome’s debugger when I would output ‘this’ it would be the browsers window object, not my parents object.  This told me something was screwed up but I could not find the cause.  That was until I started walking the call stack to see WHERE PerformSearch was being called.  Turns out PerformSearch was being called by jQuery… that was odd.  In fact below is the code making the call.


Again, why was jQuery calling my method I had not told it to.  Well I kept walking the stack and I realized that this was being called during a .ajax call as seen below.


It turns out that the ‘data’ object I was passing across the wire was not just a property bag, but it had methods.  These methods referenced ‘this’ and when jQuery tried to searlize the object it is executing the functions, and when it does the ‘this’ context is wrong and BOOM.

To solve this issue I simply refactored my code to NOT have a method and then it just worked.

My question is this.  Is what I was doing just dumb and I was an idiot, or is there a way to tell jQuery to NOT try and call my methods during serialization? 

Till Next time,

P.S. I know I could have guarded against this in my method by checking that ‘this != window’ but that felt dirty and I had a better solution.

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.


Published at DZone with permission of Derik Whittaker, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}