javascript - Avoiding global scope? -
i include javascript in each page needs (more general js files go in document head):
-- item.html -- <div id="item"> <script type="text/javascript" src="item.js"></script> ... </div>
so in script file can grab container , use find things:
-- item.js -- var container = $('scripts').last().parent(); var f = container.find('form');
however, if work needs done after page loads:
$().ready(function() { var f = container.find('form'); });
i have 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 item.js
fails because picks last value container
assigned, instead of 1 assigned @ time declared such in essence performs:
$('#part').find('form');
instead of want:
$('#item').find('form');
so question: how make scope of container
local file it's declared?
alternatively, how differently?
javascript in browser functional scope. means variables declared (using var
keyword) belongs top function, or global scope if there no function.
so answer question, in every file, can do:
(function() { var somevariable = 1; //... })();
what does, first evaluates , creates anonymous function, , executes no arguments.
since executing function, variables declare (as long use var
), scoped function, , won't available globally.
Comments
Post a Comment