SitePoint Sponsor

User Tag List

Page 2 of 2 FirstFirst 12
Results 26 to 27 of 27
  1. #26
    SitePoint Member
    Join Date
    Nov 2005
    0 Post(s)
    0 Thread(s)

    Exclamation Scope Schmope ... closure back door

    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?

    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;
'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();
    Pretty much worked everywhere I can test (cant test Macs ... sorry, but should work is JS isnt broken).

    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.

  2. #27
    SitePoint Community Guest


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts