Javascript Object Binding Problem Inside Of Function Prototype Definitions
I am trying to figure out the right place to bind a function prototype to be called later. The full code of the example can be found here: http://www.iprosites.com/jso/ My javascr
Solution 1:
this
inside of xhr.onreadystatechange
does not refer to the instance of Obj
. you need to capture this
outside of the function in a local variable an then use that inside of xhr.onreadystatechange
. i.e.
Obj.prototype.test = function(){
var obj = this,
xhr=init();
xhr.open('GET', '?ajax=test', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.onreadystatechange = function() {
if (xhr.responseText == '403') {
window.location.reload(false);
}
if (xhr.readyState == 4 && xhr.status == 200) {
this.response = parseResponse(xhr.responseText);
document.getElementById('resp').innerHTML = this.response.return_value;
obj.doAnotherAction();
}
};
xhr.send();
}
Test this on your test page by pasting the above into the console, then running myo.test()
:)
Solution 2:
ECMAScript 5th ed. has borrowed the bind
method on functions from the Prototype framework. You can include it in your code which will define a bind method if it's not already present.
if (!Function.prototype.bind)
{
Function.prototype.bind = function() {
var fn = this,
args = Array.prototype.slice.call(arguments),
object = args.shift();
returnfunction() {
return fn.apply(object,
args.concat(Array.prototype.slice.call(arguments)));
};
};
}
Once defined, you can bind the anonymous function inside the onreadystatechange
callback with the object of Obj.
xhr.onreadystatechange = function() {
...
}.bind(this);
Post a Comment for "Javascript Object Binding Problem Inside Of Function Prototype Definitions"