Isn't that pretty much *exactly* what Closure (computer science), an abstraction binding a function to its scope?
Meaning what? ALL in scope variables will WIN over global or parent calling scope. So all this heroic singleton and reseting of self and blah blah blah isnt really needed, is it? Or am I smoking crack?
Pretty much worked everywhere I can test (cant test Macs ... sorry, but should work is JS isnt broken).Code:var self = 0; // Just to give a non-OO default function ScopeTest() { // Closure *should* keep this King Of The Hill ... lets see. var self = this; this.message = 'Greetings from ScopeTest!'; this.doTest = function() { //Note : NOT setting self here ... will it remain???? try { // Try to create object for Firefox, Safari, IE7, etc. this.req = new XMLHttpRequest(); } catch (e) { try { // Try to create object for later versions of IE. this.req = new ActiveXObject('MSXML2.XMLHTTP'); } catch (e) { try { // Try to create object for early versions of IE. this.req = new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) { // Could not create an XMLHttpRequest object. return false; } } } this.req.open('GET', '/index.html', true); // split off just to make REALLY sure that 'self' is in the closure and not just valid here and now. this.req.onreadystatechange = this.doReply; this.req.send( null ); }; this.doReply = function() { //Note : NOT setting self here ... will it remain???? if ( 4 == self.req.readyState ) { var result = 'self.message is ' + self.message; result += '\n'; result += 'this.message is ' + this.message; alert( result ); } }; //Note : For me, setting/resetting self was not an issue ... worked perfectly! // checked opera (linux+win), firefox (linux+win), i.e. (+maxthon flavor) } var test = new ScopeTest(); test.doTest();
I much prefer to set self 1 time instead at the top of every method. And MUCH prefer that to classifing it as singleton to justify referencing a global (ugg) variable.
Note: 'this' is still referenced where leagle ... this was just a copy and paste of the ScopeTest and I didn't change that much.



Bookmarks