javascript - Calling a function with same name in another JS file -
i'm bit confused here... if have 1 .js
file function this:
function mymain() { var count=0; count++; myhelper(count); alert(count); } function myhelper(count) { alert(count); count++; }
can still phone call method myhelper()
on other .js file? or there other way can pass count variable 1 function called other .js file. have thought regarding one? thanks!
when both script files included in same page, run in same global javascript context, 2 names overwrite each other. no, can not have 2 functions in different .js files same name , access both of them you've written it.
the simplest solution rename 1 of functions.
a improve solution write javascript modularly namespaces, each script file adds minimum possible (preferably 1) objects global scope avoid naming conflicts between separate scripts.
there number of ways in javascript. simplest way define single object in each file:
// in first script file var modulename = { mymain: function () { var count=0; count++; myhelper(count); alert(count); } myhelper: function (count) { alert(count); count++; } } // in later script file: modulename.mymain();
a more popular method utilize self-evaluating function, similar following:
(function (window, undefined) { // code, defining various functions, etc. function mymain() { ... } function myhelper(count) { ... } // more code... // list functions want other scripts access window.modulename = { myhelper: myhelper, mymain: mymain }; })(window)
javascript function variables count
No comments:
Post a Comment