troubleshooting Question

JavaScript - Loss of scope in event handlers - self/this

Avatar of Dale Burrell
Dale BurrellFlag for New Zealand asked on
6 Comments1 Solution315 ViewsLast Modified:

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)
        else alert ("Failed to open connection");
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 6 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 6 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros