Calling a function with same name in another JS file - javascript

I'm just a bit confused here... If I have one .js file with function like this:
function myMain() {
var count=0;
count++;
myHelper(count);
alert(count);
}
function myHelper(count) {
alert(count);
count++;
}
Can I still call another method myHelper() on the other .js file? Or is there any other way that I can pass the count variable from one function to another then it will be called to other .js file. Do you have any idea regarding this one? Thanks!

Update: Nowadays you should prefer to use ES6 import/export in a <script> tag with type="module" or via a module bundler like webpack.
When both script files are included in the same page, they run in the same global JavaScript context, so the two names will overwrite each other. So no, you can not have two functions in different .js files with the same name and access both of them as you've written it.
The simplest solution would be to just rename one of the functions.
A better solution would be for you to write your JavaScript modularly with namespaces, so that each script file adds the minimum possible (preferably 1) objects to the global scope to avoid naming conflicts between separate scripts.
There are a number of ways to do this in JavaScript. The simplest way is to just define a single object in each file:
// In your first script file
var ModuleName = {
myMain: function () {
var count=0;
count++;
myHelper(count);
alert(count);
},
myHelper: function (count) {
alert(count);
count++;
}
}
In a later script file, call the function
ModuleName.myMain();
A more popular method is to use a self-evaluating function, similar to the following:
(function (window, undefined) {
// Your code, defining various functions, etc.
function myMain() { ... }
function myHelper(count) { ... }
// More code...
// List functions you want other scripts to access
window.ModuleName = {
myHelper: myHelper,
myMain: myMain
};
})(window)

If you know you are about to overwrite a method, you can store the old one first in a variable and then call the other implementation of the function via that variable.

Yes, you can call myHelper() from any other js file as long as you include both js files in one html or jsp page
you may want to look at this :
Can we call the function written in one JavaScript in another JS file?

Related

Accessing variables and methods from another file

In this case, How do I access the variable and method declared in a file from another file?
File one
jQuery(function(t) {
var myVar = 'myValue',
e = function(t) {
console.log('myLog');
}
});
File two
jQuery(function($){
// ????
});
You don't. It has nothing to do with files (JavaScript largely doesn't care about files unless they're ES2015+ modules), it has to do with the fact that both myVar and e are entirely private to the anonymous function you're passing into jQuery in the first code block. Even other code outside that function in the same file would be unable to access them.
You'd have to change the first file to make that information accessible outside that function. You could do that by making them globals (blech), or by having a single global you use for all of your things like this with an object with properties for these things (slightly less "blech" :-) ), or by using something like Webpack and true modules.
It really depends on how you setup your scripts. For instance:
<script src="fileOne.js"></script>
<script src="fileTwo.js"></script>
Then you will be able to do the following:
File One:
- Declare variable x
File Two:
- Access variable x
I recommend taking a look at this, it'll help with understanding variable scope (however this doesn't cover ES6's let): https://www.w3schools.com/js/js_scope.asp

How to use function declared in different JS file using jQuery getScript?

I have two JS files. One is called common.js and it use $.getScript to include other file with my js code. Part of including looks like this:
jQuery.getScript(js_path + "table.js", function(){
generateTable(chartData, dataTypes);
});
This file (common.js) also contains function compare(a, b).
Now, the second one (table.js) has declared different function which uses the compare function from the first file. Something like this:
function someName() {
var a = 2,
b = 5;
var test = compare(a, b);
return test;
}
When I run the code it gives me:
Uncaught ReferenceError: compare is not defined
How can I use function from the first file.
jQuery.getScript first fetches the JS file from the server, then executes it. If you want to work with global functions (as it seems) you need to pay attention to the following:
Your compare function must be declared before the table.js file is executed.
The compare function must be declared on the global namespace of table.js.
Sorry but without more info this is all you can get.
If your main file, as something like:
(function() {
function compare(){...}
}());
Then the compare function is not declared in the global namespace.
did you check the order of imports? The file with 'compare' method should be first. It should solve the problem.
What I would suggest is to skip getScript if it's just for separating the code.
<script src="common.js"></script>
<script src="table.js"></script>
<script src="app.js"></script>
Where common functions go into common, your table stuff goes into table. This way you get the ordering right. This also clears out the circular dependency one might see a hint of if table depends on common that depends on table by extracting all but the 'common' parts into some form of 'app'.

Multiple Javascript files, I want to take out URL constants into a seperate file

As the title says, I have a few javascript files. There are sections that call a few websites. I want to be able to store the websites in a different file, this way if the website changes we just need to make one change and not many.
Any suggestions?
I tried doing something like
/**
* Returns URLs
*/
var URLCONTEXT = "/root-url/context/";
var URLROOT = "/root-url/";
function getContextUrl(){
return URLCONTEXT;
}
function getRootUrl(){
return URLROOT;
}
but this doesn't have a way to communicate with the other JS files =/
Include your url constants in a js file like
url-constants.js
var URLCONTEXT = "/root-url/context/";
var URLROOT = "/root-url/";
and reference this js file first before other js files.
and you will be able to use url-constants variable in any other js file.
other.js
function getContextUrl(){
return URLCONTEXT;
}
function getRootUrl(){
return URLROOT;
}
include these in your page like
<script language="text/javascript" src="url-constants.js"></script>
<script language="text/javascript" src="other.js"></script>
var's defined outside of a function, and functions defined with a name are in the global namespace. You can access them from your other JS files as long as this JS file is loaded first.
You should be able to do that. Just make sure the file with the urls is included before the files where it's accessed from.
Also, I would not recommend polluting the global scope with these, even if you named them in capital letters. How about defining
var URLS = {
urlContext: '/root-url/context',
urlRoot: '/root-url'
};
and using them in other files with URLS.urlContext and URLS.urlRoot?

javascript linking

I'm going to build a rather complicated application in html5 with some heavy javascripting.
In this I need to make some objects which can be pass around. But since there is no like #import foobar.js.
Then I assume that if my html page loads the scripts, then all the scripts can access eachother?
I read (here) that ajax somehow is able to load a .js file from within another .js file. But i dont think this is what I need?
Can go more into details if needed, thanks in advance.
In our projects, we do the following: Suppose you're going to call your project Foo, and have a module called Bar in it,
Then what we do is declare a file called Foo.js that just defines an equivalent to a Foo namespace:
Foo = (function(){
return {
};
})();
Then we create a file called Foo.Bar.js that contains the code for the Bar module:
Foo.Bar = (function(){
// var declarations here that should be invisible outside Foo.Bar
var p, q;
return {
fun1 : function(a, b){
// Code for fun1 here
},
fun2 : function(c) {
// Code for fun2 here
}
} // return
})();
Note that how it is a function that executes immediately, and returns an object that gets assigned to Foo.Bar. Any local variables, like p and q are available to fun1 and fun2 because they're in a closure, but they are invisible outside of Foo.Bar
The functions in Foo.Bar can be constructors for objects and so on.
Now in your HTML you simple include both files like so:
<script type="text/javascript" src="Foo.js"></script>
<script type="text/javascript" src="Foo.Bar.js"></script>
The result will be that you can call Foo.Bar's functions in the JavaScript of your main HTML file without any problems.
You should check out the module pattern:
http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth/
This describes alternatives for creating modular code in javascript, how you can protect your code and share APIs and data among them.
You should also consider using and AMD. Require.js is quite popular, but I tend to prefer head.js for this. Keep in mind that these put some requirements on how you structur your code in files, and personally, I don't think it's worth it, compared to a concatenated and minified file included in the bottom of the page.
Then I assume that if my html page loads the scripts, then all the scripts can access eachother?
Yes.

calling a javascript function from a separate script?

I want to organize my JavaScript so I thought I would make a functions JS file. Is there anyway I can call the functions from functions.js from global.js?
EDIT
functions.js:
var get_selects;
get_selects = {
getLanguages: function() {
}
}
global.js:
get_selects.getLangueges();
Yes, functions defined at the top level are automatically available in the global scope (window in a browser), and this is typically not desirable.
Another approach that would mitigate this is to group your functions into a single object so you aren't polluting the global scope with a whole bunch of unrelated functions.
var utils;
utils = {
toast: function(message) {
alert("Notification: " + message);
},
sum: function(a, b){ return a + b; }
}
utils.toast('Email sent');
utils.sum(1, 2);
If both scripts have been included in the same HTML file, sure, it will work out of the box. Best way to know is to try it.
All .js files load top level functions into the global namespace. So, yes.
simply call it like anyother functions
yourFunctionName(yourFunctionParams);
be aware, you need to include your functions.js BEFORE your global.js, else it won't see your functions.
From the moment you include a JS in the HTML file, all the functions become available. So, if you make like this, it will work:
<script type="text/javascript" src="functions.js"></script>
<script type="text/javascript" src="global.js"></script>
But (as soon as I know), you must include "functions.js" first. Otherwise, "global.js" will not be able to find the calls. You can also make a little function inside "global.js" to include "functions.js" on the fly, like this:
function include(js_path){
//By Fabrício Magri e Micox
//http://elmicox.blogspot.com/2006/12/include-em-javascript.html
var new= document.createElement('script');
new.setAttribute('type', 'text/javascript');
new.setAttribute('src', js_path);
document.getElementsByTagName('head')[0].appendChild(new);
}
Than, on the beginning of your "global.js" you call this function to include the contents of "functions.js" on the section as soon as the browser requests "global.js"

Categories

Resources