Dale Burrell
asked on
JavaScript - Loss of scope in event handlers - self/this
Guys,
Its a common problem with a common soloution and I've used it loads myself... but I'm missing something probably quite obvious here in understanding why the solution actually works.
See following code, I'm creating and assigning an event handler and prior to creating the event handler I'm making a reference 'self' to the 'this' pointer so that I can access it when the event handler is called. Now I understand why the 'this' pointer is no longer in scope... what I don't understand is why a local variable, 'self', IS in scope when called from within the event handler. So if someone could clarify that small point for me I'llk be very happy...
Cheers Dale - Code follows...
this.makeRequest = function()
{
if (this.Init())
{
this.request.Open(this.met hod, this.url, this.async);
var self = this;
this.request.onreadystatec hange = function()
{
if(self.request.readyState == 4)
{
}
}
this.request.send(this.pos tData)
}
else alert ("Failed to open connection");
}
Its a common problem with a common soloution and I've used it loads myself... but I'm missing something probably quite obvious here in understanding why the solution actually works.
See following code, I'm creating and assigning an event handler and prior to creating the event handler I'm making a reference 'self' to the 'this' pointer so that I can access it when the event handler is called. Now I understand why the 'this' pointer is no longer in scope... what I don't understand is why a local variable, 'self', IS in scope when called from within the event handler. So if someone could clarify that small point for me I'llk be very happy...
Cheers Dale - Code follows...
this.makeRequest = function()
{
if (this.Init())
{
this.request.Open(this.met
var self = this;
this.request.onreadystatec
{
if(self.request.readyState
{
}
}
this.request.send(this.pos
}
else alert ("Failed to open connection");
}
ASKER
I don't care what it is called - can you explain the scoping?
Thanks,
Thanks,
mplungjan's right - get rid of the 'self' first, then debug from there:
this.makeRequest = function()
{
if (this.Init())
{
this.request.Open(this.met hod, this.url, this.async);
var obj = this;
this.request.onreadystatec hange = function()
{
if(obj.request.readyState == 4)
{
}
}
this.request.send(this.pos tData)
}
else alert ("Failed to open connection");
}
this.makeRequest = function()
{
if (this.Init())
{
this.request.Open(this.met
var obj = this;
this.request.onreadystatec
{
if(obj.request.readyState == 4)
{
}
}
this.request.send(this.pos
}
else alert ("Failed to open connection");
}
ASKER
Guys... pay attention... the code works! I'm just trying to make sense of it... cheers
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks dude... just what I was looking for...
Try another name for the var