what is ‚this‘ in js revisited

today, we had a strange question coming up: we make heavy use of ’namespaces‘ in javascript in order not to pollute too much the document or window object. So, we do something like:

CL = {
  Namespace : {
    functions : {
      onload : function() {
            // things to be done in this function
       }
    }
  }
}

but, what, if the onload function contains code like:

this.x = 42;

this in that example is CL.Namespace.functions (!). That is extremely confusing, because this in an object refers to the instance of the object itself. So a functiondefinition within that namespace would surely use ‚this‚ as a keyword and the this than depends on the usage of the function.

So, i would strongly discourage the use of ‚this‚ in a namespace, even it seems to be allowed according to this information: http://www.quirksmode.org/js/this.html. I have done a little bit of coding to show the full desaster on this:
sourceexample: https://github.com/chleverenz/JSSamples/blob/master/thispointer.html

Veröffentlicht in programming. Leave a Comment »