I’m trying a more object oriented approach with javascript and have implemented a class with some methods through the use of class.prototype.
But I have a problem.
I tried to use a method from myclass as the success function of an ajax call. The issue is I can’t use this withing that method when is called back by ajax. I.E:
MyClass.prototype.myMethod = function(data)
{
this.data = data; /* in here this is the window object */
}
var myClass = new MyClass();
$.ajax:
success:myClass.myMethod;
Am I doing something wrong?
Edit: Full function to try
am not i am
method
function MyClass()
{
this.name="myclass";
};
MyClass.prototype.print = function()
{
alert(this.name);
};
var myAjax = function(context_,func)
{
$.ajax({
url:"www.google.com",
type: "GET",
context:context_,
complete:function(data){
func(data);
}
});
};
var refreshGroups = function(groups)
{
var myClass = new MyClass();
myAjax(myClass,myClass.print);
return;
}
Result: alert is empty
Use the
context:property of the$.ajaxcall.or use
$.proxy…Given the updated code, you’d need to change
func(data)to be called from the calling context that you set usingcontext:, so you dothis.func(data)……but since you’re not doing anything in that anonymous function other than calling the function you passed, and passing on the argument, you could just do
complete:func……and the calling context of
funcwill be set to the object you passed, and thedataargument will still be passed to the function.Of course, this really isn’t an issue the way your code works, because you already have a closed reference to your context, so you could just as well skip passing the
func, and just get it right from your object…