Ryan
Ryan

Reputation: 10049

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 variables, 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!

Upvotes: 1

Views: 462

Answers (3)

nobody
nobody

Reputation: 10635

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.

Upvotes: 0

user113716
user113716

Reputation: 322452

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.

Upvotes: 5

timw4mail
timw4mail

Reputation: 1766

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.

Upvotes: 0

Related Questions