Placing JavaScript functions inside of an object of a variable -
i see quite often, i'm not sure purpose of or advantages (if any). placing function or sets of functions inside of object, value variable.
var variablename = { (function() {do stuff} )}
javascript uses global variables. means every script cann access , modify variables , possible overwrite variables same name. secure own script, can use global variable (like var myscript=... ) , write it. give example, wrote simple script navigate between html-files. can see variable called 'navi' capsulates stuff inside. contains variables , functions , (in case) access allowed returned names. if wrote functions next , previous out of navi, may overwritten in other scripts.
var navi = (function(){ var currentpage = 0; var pages = []; pages[0] = "first.html"; pages[1] = "second.html"; pages[2] = "third.html"; var next = function next(){ if(currentpage < pages.length - 1){ currentpage++; location.href = pages[currentpage]; } }; var previous = function previous(){ if(currentpage > 0){ currentpage--; location.href = pages[currentpage]; } }; return{ next: next, previous: previous, currentpage: currentpage, pages: pages }; })();
to call html file:
<a href="javascript:navi.previous();">previous page</a> <a href="javascript:navi.next();">next page</a>
so far.
Comments
Post a Comment