How to best use `this` inside a closure?

40 views
Skip to first unread message

Roman Snitko

unread,
Mar 5, 2013, 7:48:44 PM3/5/13
to jsclas...@googlegroups.com
Let's say I have this code:

MyClass = new JS.Class({
 
  initialize: function() {
    var self = this;
    $("#editor").change(function() {
      self.call_some_method_on_my_class();
    });
  }
  
});

it all works, but it sucks to always have to define a `self` variable in every MyClass method where I have to pass a callback in which I need to refer back to my object. What is the best way to avoid this?

Anthony Rowlands

unread,
Mar 5, 2013, 7:50:39 PM3/5/13
to jsclas...@googlegroups.com
Since you're using jquery, check out $.proxy

http://api.jquery.com/jQuery.proxy/
--
You received this message because you are subscribed to the Google Groups "jsclass-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jsclass-user...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

James Coglan

unread,
Mar 17, 2013, 4:51:28 PM3/17/13
to jsclas...@googlegroups.com
This is how I do it. Some JS APIs let you pass in an object to bind `this` to inside a callback, e.g.

list.forEach(function(item) {
  this.add(item);
}, this);

Here, the final argument of `this` makes the callback function execute with the correct `this` binding. This approach is unfortunately not widely supported by JS libraries, so you need to use self=this or Function.bind or one of its variants (e.g. jQuery.proxy).
Reply all
Reply to author
Forward
0 new messages