Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Typescript, jQuery and the ‘this’ context causing issues

DZone's Guide to

Typescript, jQuery and the ‘this’ context causing issues

· Web Dev Zone
Free Resource

Add user login and MFA to your next project in minutes. Create a free Okta developer account, drop in one of our SDKs to your application and get back to building.

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.

image

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.

image

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.

image

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.



Launch your application faster with Okta’s user management API. Register today for the free forever developer edition!

Topics:

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

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}