I want to access an object’s own function from a jQuery method which fails.
function obj(){
this.send = function(){
$.get("send.php",null,function(data){
this.success();
}).error(function(){ this.fail(); });
}
this.fail = function(){
alert("fail");
}
}
var o = new obj();
o.send();
Gives this error: TypeError: this.fail is not a function
How to access function fail inside jQuery?
On line 5,
failis not called by the same object, sothisdoes not have the same reference, and therefore no method fail. We say that you change context.The trick is to use a variable often called
selforthator_this. I preferself.It should make it, and yes, javascript looks like a pity language. But once you overcome the few problems, you will love the possibilities.