Avoiding global scope?

ekkis

I like to include my javascript in each page that needs it (more general js files go in the document head):

-- item.html --
<div id="item">
<script type="text/javascript" src="item.js"></script>
 ...
</div>

so in my script file I can now grab the container and use it to find things:

-- item.js --
var container = $('scripts').last().parent();
var f = container.find('form');

however, if the work needs to be done after the page loads:

$().ready(function() {
    var f = container.find('form');
});

I have a problem because container scopes across files. consider:

-- index.html --
<div id="item">
<script type="text/javascript" src="item.js"></script>
 ...
</div>
<div id="link">
<script type="text/javascript" src="link.js"></script>
 ...
</div>
<div id="part">
<script type="text/javascript" src="part.js"></script>
 ...
</div>

where the item.js fails because it picks up the last value container was assigned, instead of the one it was assigned at the time that it was declared such that it in essence performs:

$('#part').find('form');

instead of what I want:

$('#item').find('form');

so my question: how do I make the scope of container local to the file where it's declared?

alternatively, how could I do this differently?

Norman Breau

JavaScript in the browser is functional scope. Which means variables declared (using the var keyword) belongs to the top most function, or the global scope if there is no function.

So to answer your question, in every file, you can do:

(function() {
    var someVariable = 1;
    //...
})();

What this does, is first evaluates and creates the anonymous function, and then immediately executes it with no arguments.

Since you are executing a function, any variables that you declare (as long as you use var), will be scoped to the function, and won't be available globally.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related