One could say that the behaviour of “this” in JavaScript is rather unconventional, at least when you have a strong object-oriented background like I do. For example, libraries like jQuery change the scope of event listeners which does not allow you to refer to a surrounding object (think an object’s method is used as an event listener and in this method you try to access the object’s properties through “this”).
To maintain the scope we can create closures which make sure that the appropriate scope is set when the function / listener is called.
I ran into this issue when I wrote my first bigger (> 7000 lines of code) object-oriented JavaScript application. Additionally, you can find a QUnit test in the following listing. It shows how you can tell whether the correct scope was applied.
That's me, Ben.
Hey, I am Ben Ripkens (bripkens)
and this is my blog.
I live in
Düsseldorf
(Germany)
and I am employed by the
codecentric AG as a Software Engineer.
Web application frontends are my main area of expertise, but you may also
find some other interesting articles on this blog.