I sincerely agree that too many built-in closure functions do not improve readability. On the other hand, I strongly dislike the var self = this style for writing closures, to which this is just an option, because it is still too verbose in your declaration, and you enter your own new keyword, whether this or self .
What you want is a curry / snap method.
function $A(o) { var a = []; for (var i = 0; i < o.length; ++i) a.push(o[i]); return a; } Function.prototype.bind = function() { var _method = this; var a = $A(arguments) var o = a.shift(); return function() { return _method.apply(o, a.concat($A(arguments))); } } Function.prototype.curry = function() { var _method = this; var a = $A(arguments); return function() { return _method.apply(null, a.concat($A(arguments))); } }
Methods taken from the Prototype library. I use them even in projects that do not use the Prototype library, as they are very useful!
In your case, this means instead of writing:
var This = this; oRequest.onreadystatechange = function() { This.handleResponse(oRequest, sUsername) }
now you can write:
oRequest.onreadystatechange = this.handleResponse.curry(oRequest,sUsername);
However, if you want to convey the meaning of this keyword, you can do it
oRequest.onreadystatechange = this.handleResponse.bind(this,oRequest,sUsername);
handleResponse when called will have the same this context as submitHandler .
source share