Javascript: Variables being leaked into the global scope (Firefox addon)
I submitted my addon to the AMO direcotry and the editor came back with this:
There are still a number of variables being leaked to the global scope,
probably because you're using them undeclared like...
He did not mention all the problem var开发者_运维问答iables, is there anyway to know which are in global scope / getting leaked?
I have a crapload of variables and it would take ages going through each one of them to make sure they were declared properly with a "var".
Please help!
Thanks!
If you're trying to track down variables that may have been implicitly declared as global because of the omission of var
, you could run the code in strict mode
. This will give you a ReferenceError
if you try to use variables that haven't been property declared.
(function() {
"use strict"; // <-- this runs code inside this function in strict mode
// your code...
test = 'tester'; // gives a ReferenceError
})();
You'll need to run it in a supported browser, like Firefox 4 or higher. The "use strict";
declarative will ensure that any code inside the function will be evaluated using the rules of strict mode.
Besides properly using the var keyword, you should make sure all your javascript is wrappend in a function like this:
(function(){
//Your code
}());
This keeps all your variables within the scope of an immediately invoked function.
Use firefox with firebug, add a break point somewhere appropriate and watch the "window" object, all the variables within the global scope are a member of it.
精彩评论