Skip navigation.

Will Erlang Become the Next Java (or .NET)?All recent postsFun with Kinematic Typography

MS AJAX Library and JQuery: What Does 'this' Point To?

Seeing so many JQuery fans out there, I’d like to share a little trick I use when I run JQuery alongside the MS AJAX Library.

There’s one very confusing aspect of JavaScript: the this keyword. What does this point to at any given time? The answer is it depends. It’s often difficult to figure it out. Just about the best and most detailed explanation of JavaScript closures, execution contexts, scope chains, the this keyword, etc, is here: JavaScript Closures.

When you write a new client-side component—a behavior or a client control—you declare a “constructor” and then augment the “class” prototype:

MyNamespace.MyControl = function (element) {
  MyNamespace.MyControl.initializeBase (this, [element]);
  // ...
  this._addPanel = null
}

MyNamespace.MyControl.prototype = {

  initialize: function () {
    MyNamespace.MyControl.callBaseMethod (this, 'initialize');    
    
    var self = this;
    var el = self.get_element();
        
    // ...
    var addLink = document.createElement ('a');
    $(addLink).click (function (evt) { 
       $(self._addPanel).show ();
       evt.preventDefault ();
    });
    // ...
  }
}

I simply save this because I know it’ll change hands inside various closures. It’s easy enough to forget you’re inside a closure when writing a mad “jquery” so this doesn’t point to your component anymore.

In the sample above I have a hyperlink whose click handler should display an arbitrary panel. I store this panel DOM element in a “private” field of my component. I can’t write $(this._addPanel).show() because this will point to the hyperlink when the click handler is invoked. Saving this in variable self allows me to get to the panel.

This simple technique has saved me a lot of debugging time. Hope it helps someone.

Comments

Comment permalink 1 Josh Stodola |
Great technique! Thanks for sharing ;)
Comment permalink 2 Morten |
Alternative you can create a delegate to make 'this' valid in the eventhandler context:
$(addLink).click (Function.createDelegate(this,function (evt) {
$(this._addPanel).show ();
evt.preventDefault ();
}));

Emails and Notifications

Would you like to be notified when somebody responds to this post?  Would you like to have these comments emailed to you?

Submit your comment

Please enter only text since all HTML tags except hyperlinks will be stripped. Hyperlinks will become live links. Any comments with flaming or offensive language will be deleted. Be courteous to other posters. Thank you.

Your name (required):
Your email (optional):
Your site's URL (optional):
Enter this number
Type in the number above:
Comment (required):