Skip to content

Double bind() for better `this` experience

I am doing some developing with prototype lately and I was having some issues with context of `this` variable. The problem is that javascript is different from python in a way that defines local variable scope of class methods.

So here is short snippet with double bind(this) that allows one to reference class `this`. In essence, you just have to make sure that every call is wrapped into bind(this) if you want to be able to access `this` of class instance.


// class code goes around and params dict
new Ajax.Request('json-url',
{ parameters: params,
method: 'post',
onSuccess: function(transport) {
response = transport.responseText.evalJSON();
response.images.map(function(i) {
this.local_func(i.image.prop);
}.bind(this));
}.bind(this)
});