Measuring pollution of global namespace

javascript, namespaces, refactoring

Solution

The general pattern you've selected works OK from experience. However, there are two things you might need to consider (as additions or alternatives):

- Use JsLint.com or JSHint.com with your existing code and look at the errors produced. It should help you spot most if not all of the global variable usage quickly and easily (you'll see errors of 'undefined' variables for example). This is a great simple approach. So, the measurement in this case will be just looking at the total number of issues.

- We've found that Chrome can make doing detection of leaking resources on the window object tricky (as things are added during the course of running the page). We've needed to check for example to see if certain properties returned are native by using RegExs: `/\s*function \w*\(\) {\s*\[native code\]\s*}\s*/` to spot native code. In some code "leak detection" code we've written, we also try to (in a try catch) obtain the value of a property to verify it's set to a value (and not just undefined). But, that shouldn't be necessary in your case.

Problem

Background I'm trying to refactor some long, ugly Javascript (shamefully, it's my own). I started the project when I started learning Javascript; it was a great learning experience, but there is some total garbage in my code and I employ some rather bad practices, chief among them being heavy pollution of the global namespace / object (in my case, the `window` object). In my effort to mitigate said pollution, I think it would be helpful to measure it. Approach My gut instinct was to simply count the number of objects attached to the `window` object prior to loading any code, again after loading third-party libraries and lastly after my code has been executed. Then, as I refactor, I would try to reduce the increase that corresponds to loading my code). To do this, I'm using: `console.log(Object.keys(window).length)` at various places in my code. This seems to work alright and I see the number grow, in particular after my own code is loaded. But... Problem Just from looking at the contents of the `window` object in the Chrome Developer console, I can see that its not counting everything attached to the object. I suspect it's not including some more fundamental properties or object types, whether they belong to the browser, a library or my own code. Either way though, can anyone think of a better and more accurate way to measure global namespace pollution that would help in refactoring? Thanks in advance!

Original source