Call functions from different .js documents

I have 2 functions from two types of different .js documents.

File1.js

$(document).ready(function Function1(){
    var $input = $("#input-country");
    $input.typeahead({source:['United States', 'China', 'Germany']});
});

File2.js

$(document).ready(function Function2(){
    var $input = $("#input-country");
    $input.typeahead({source:['Menu 1', 'Menu 2', 'Menu 3']});
});

I created global js which called 2 functions global.js

Global.js

$(function TestName() {
    Function1();
    Function2();
});

When importing files, only what is in order works.

<script src="js/File1.js"></script>
<script src="js/File2.js"></script>

In this case, only File1.js works, the second does not.

or

<script src="js/File2.js"></script>
<script src="js/File1.js"></script>

In this case, only File2.js works, the first does not work.

+4
source share
1 answer

First of all, you should try to avoid polluting the global namespace where possible, however, common functions in a web browser can be achieved by assigning a window object as follows:

// File 1 - using an immediately invoked function expression (IFFE)
(function(global) {
  // make available globally:
  global.funcOne = myFunc;

  var privateVariable = 1;

  function myFunc() {
    return privateVariable;
  }
}(window));

// File 2 - using an immediately invoked function expression (IFFE)
(function(global) {
  // make available globally: 
  global.funcTwo = myFunc;

  var privateVariable = 2;

  function myFunc() {
    return privateVariable;
  }   
}(window));

// your "global" js file (using the jquery document ready wrapper):
$(function() {
   console.log(funcOne() + funcTwo()); // returns 3
});

JsFiddle, .

. IFFE ECMAScript > .

, :

// File 1
(function(global, $) {
    // make available globally:
  global.setCountries = setCountries;
  // private variable:
  var data = {source:['United States', 'China', 'Germany']};
  function setCountries() {
    $("#input-country").typeahead(data);
    console.log('setCountries() Called!'); // not required.
  }
// dependencies:  
}(window, jquery));

// File 2
(function(global, $) {
    // expose global function:
  global.setMenu = setMenu;
    // private variable:
    var data = {source:['Menu 1', 'Menu 2', 'Menu 3']};
    // private function:
  function setMenu() {
    $("#input-country").typeahead(data);
    console.log('SetMenu() Called!'); // not required.
  }
// dependencies:
}(window, jquery));

// Global Js
$(function() {
   function TestName() { 
       setMenu();
       setCountries();
   }
   TestName();
});
+1

Source: https://habr.com/ru/post/1672075/


All Articles