Preventing auto-creation of global variables in Ja

2019-04-10 07:53发布

I just spent some time debugging a problem that boiled down to forgetting to use the var keyword in front of a new variable identifier, so Javascript was automatically creating that variable in the global scope. Is there any way to prevent this, or change the default behavior, without using a validator like JSLint?

Running a validator in between writing and executing Javascript code seems like a poor excuse for compiling, which is the step I'd usually rely on to catch this sort of thing.

I'm guessing the answer is a "no," so I'm looking into a JSLint Eclipse plugin as I post this.

6条回答
太酷不给撩
2楼-- · 2019-04-10 08:34

I made a bookmarklet some time ago to inspect and detect global variables.

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

It has some additional features (like filtering out Prototype.js or Google Analytics properties) too.

查看更多
等我变得足够好
3楼-- · 2019-04-10 08:35

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

查看更多
手持菜刀,她持情操
4楼-- · 2019-04-10 08:40

The answer is indeed no - but you could use the Eclipse plugin as you said, which can as far as I know run when saving etc., so it won't require additional steps.

IntelliJ IDEA is also able to spot undeclared variables. IntelliJ does it real-time as you type and can also analyze your codebase jslint-style. Probably some other alternatives too.

查看更多
劫难
5楼-- · 2019-04-10 08:41

Not that I know of -- JS developers have historically been adverse to adding "seat belts" to the core language, so they've been implemented in external tools like JSLint instead. You might consider adding JSLint to your build/test process via it's Rhino version, and make the test suite fail if JSLint reports errors.

查看更多
神经病院院长
6楼-- · 2019-04-10 08:48

Install Firebug, and enable it on your site. It will complain each time you create a global without var, as well as some other situations which you might or might not want to catch.

You can also do this using the about:config option javascript.options.strict, but since that's global it'll affect all the other sites you browse too.

查看更多
孤傲高冷的网名
7楼-- · 2019-04-10 08:53

ES5 strict mode prevents automatic creation of global variables, but it's probably going to be a year before there are any shipping browsers that recognise strict mode, so JSLint is probably your best bet until then :-/

查看更多
登录 后发表回答