Prevent auto-creating global variables in javascript

I just spent some time debugging the problem, which came down to forgetting to use the var keyword before the new variable identifier, so Javascript automatically created this variable in the global scope. Is there a way to prevent this or change the default behavior without using a validator like JSLint?

Running a validator between writing and executing Javascript seems like a bad pretext to compile, which is the step I usually relied on to catch something like that.

I assume the answer is no, so I look through the JSLint Eclipse plugin when I publish this.

+4
source share
6 answers

ES5 strict mode prevents the automatic creation of global variables, but it will probably be a year before there are any delivery browsers that recognize strict mode, so JSLint will probably be the best choice until then: - /

+5
source

Check this handy bookmarklet created by Remy Sharp , you can use it to check if any variables have moved to the global namespace.

+3
source

Not that I know - JS developers have historically negatively added seat belts to their main language, so they were implemented in external tools like JSLint. You might consider adding JSLint to your build / testing process through the Rhino version and crash the test suite if JSLint reports errors.

+2
source

The answer is really no, but you could use the Eclipse plugin as you said that, as far as I know, it starts when saved, etc., so it will not require additional steps.

IntelliJ IDEA can also detect undeclared variables. IntelliJ does this in real time as you type, and can also analyze your jslint-style code. There may be other alternatives.

+1
source

I made a bookmarklet a while ago to check and detect global variables.

alt text http://yura.thinkweb2.com/detect_global.png

It has some additional features (for example, filtering Prototype.js or Google Analytics properties).

+1
source

Install Firebug and enable it on your website. He will complain every time you create a global without var , as well as some other situations that you might or might not want to catch.

You can also do this using the about:config option javascript.options.strict , but since it is global, it will affect all other sites that you are viewing.

0
source

All Articles