Neha
Neha

Reputation: 2965

call a java script function in a js file from a function of another js file

my problem is that i have two js file (1.js, 2.js), in both has the same functionality , methods(or like a copy of file). now i want to call a function (like _finish() ) from one js(1.js) file to another js file(2.js) file. can anyone give a solution.

Upvotes: 1

Views: 1087

Answers (2)

gion_13
gion_13

Reputation: 41533

I agree with jAndy. In your case you must use namespaces.
For example, if you have script one defining variable a and then the second script defining it's own variable a, when the 2 scripts are put together, the last script executed by the browser overwrites the a variable :

//script 1
var a = 'script 1 value';
// ...
//script2
var a = 'script 2 value';
// ...
alert(a);

When you execute the above example, you'll see that the second script has redefined your a variable. So, the best way to do this without having name conflicts is using namespaces:

//script 1
script1Namespace.a = 'script 1 value';
// ...
//script2
script2Namespace.a = 'script 2 value';
// ...
alert(script1Namespace.a);
alert(script2Namespace.a);

Upvotes: 0

jAndy
jAndy

Reputation: 236022

Create your own namespace and pull all "public" methods (to your application) in there.

1.js

window.yourspace = window.yourspace || {};

window.yourspace.app = (function() {
     var foo = 1;

     return {
         publicfunction: function() {
             alert('hello world');
         }
     };
}());

2.js

window.yourspace = window.yourspace || {};

if( yourspace ) 
    yourspace.app.publicfunction();

Upvotes: 3

Related Questions