KWPro.net

Javascript Trick with Objects, Closures and This
By: conark
Published On: 2-11-2010

If you work heavily with closures in Javascript (using a framework like jQuery) and you heavily program with OOP style Javascript, you might from time-to-time encounter a situation where within the closure, you want to access your object's this member.  For instance:

function MyObject(){

  this.someMethod = function(){ // blah blah };

  this.view = function(){

    $('.button').click(function(){

      this.someMethod();

    });

  };

}


You'll find that the this member no longer responds the way you want.  That's because it's now bound to the jQuery closure (I'm not sure if this is the correct terminology, but bear with me).  However, more than likely, you'll probably want to invoke your method or access a data member from your object.  So how do you handle this situation?  Use a temporary variable to hold the this member. 

function MyObject(){

  this.someMethod = function(){ // blah blah };

  this.view = function(){

    var tmp = this;

    $('.button').click(function(){

      tmp.someMethod();

    });

  };

}


Since the this member inside the click closure function gets overriden as a result of its scope, you need a kind of global variable just outside of the closure to hold your object's reference.  So storing that reference as a temporary variable will now allow you to be able to access your object's methods and data members.  I"ve often made the mistake of trying to access my this member inside a closure and forget to use a temporary variable.  So hopefully, this simple guide will help others when they encounter a similar problem

AddThis Social Bookmark Button Sphere: Related Content

Trackbacks: (Trackback URL)

No Comments Posted Yet
July [August] September
Sun Mon Tue Wed Thu Fri Sat
31 1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31 1 2 3