Link to home
Start Free TrialLog in
Avatar of Dale Burrell
Dale BurrellFlag for New Zealand

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.method, this.url, this.async);
            var self = this;
            this.request.onreadystatechange = function()
            {
                if(self.request.readyState == 4)
                {
                }
            }
            this.request.send(this.postData)
        }
        else alert ("Failed to open connection");
    }
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

I would for sure not use the reserved word self.
Try another name for the var
Avatar of Dale Burrell

ASKER

I don't care what it is called - can you explain the scoping?

Thanks,
mplungjan's right - get rid of the 'self' first, then debug from there:


    this.makeRequest = function()
    {
        if (this.Init())
        {
            this.request.Open(this.method, this.url, this.async);
            var obj = this;
            this.request.onreadystatechange = function()
            {
                if(obj.request.readyState == 4)
                {
                }
            }
            this.request.send(this.postData)
        }
        else alert ("Failed to open connection");
    }
Guys... pay attention... the code works! I'm just trying to make sense of it... cheers
ASKER CERTIFIED SOLUTION
Avatar of dakyd
dakyd

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks dude... just what I was looking for...