What is ‘this’ in JavaScript 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:

but, what if the onload function contains code like:

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 function definition 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. I have done a little bit of coding to show the full desaster on this:
source example.


No comments yet.

Leave a Reply