0

My question is how to access functions which have been created in other files. I have 3 files checkSelection.js polishToEnglish.js polishToGerman.js.

Struct of file 1 is:

//some code

function selectOptions() {
    //some code
    if (document.getElementById("Pol2Eng").checked) {
        polishToEnglish(polish2EnglishDictionaryPath, polishExpression);
    } else if (document.getElementById("Pol2Ger").checked) {
        polishToGerman(polish2EnglishDictionaryPath, polish2GermanDictionaryPath, polishExpression);
    } 
    //some code
}

The second one is:

function polishToEnglish(polish2EnglishDictionaryPath, polishExpression){
    //some code
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState === 4) {
            var lines = xmlhttp.responseText;
            dictionary = lines.split('\n');
            return findTranslation(dictionary, polishExpression);
        }
    };
    //some code
}

function findTranslation(dictionary, word) {
    dictionary.forEach(function(line){
        if(line.includes(word)) {
            result = line.split(';')[1];
        }
    });
    return result;
}

And the third one is:

function polishToGerman(polish2EnglishDictionaryPath, polish2GermanDictionaryPath, polishExpression) {
    engWord = polishToEnglish(polish2EnglishDictionaryPath, polishExpression);
}

The problem is in the third file. engWord is displayed as undefined. I've tried some solutions like making the functions window.polishToEnglish = function(...){}, but with no effect. Any ideas how to resolve the problem?

  • 1
    You can use modules `export function...` then at the top of the third `import {funcName} from ./path/to/file` – pmkro Apr 03 '19 at 20:37
  • Is `engWord` declared anywhere in the scope of the third function? If not, it will be inserted into the global scope when you assign it (`window.engWord` in a browser context). – jspcal Apr 03 '19 at 20:42
  • @pmkro I've never used modules so that will be kinda difficult to implement. – this_is_patrick Apr 03 '19 at 20:53
  • @jspcal no, it's not declared anywhere. But even after declaring it, nothing new happens. – this_is_patrick Apr 03 '19 at 20:55

1 Answers1

0

Simple solution: link to them in the right order. So:

<script src="polishToEnglish.js">
<script src="polishToGerman.js">
<script src=checkSelection.js">

since checkSelection uses declarations from both other files, and polishToGerman relies on polishToEnglish.

(Better solution would be using some sort of modules, like ES6's export-import, or CommonJS and module.exports-require).

mbojko
  • 13,503
  • 1
  • 16
  • 26