首页 > 解决方案 > 如何访问文件外的函数

问题描述

我的问题是如何访问在其他文件中创建的函数。我有 3 个文件checkSelection.js polishToEnglish.js polishToGerman.js

文件1的结构是:

//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
}

第二个是:

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;
}

第三个是:

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

问题出在第三个文件中。engWord显示为未定义。我尝试了一些解决方案,例如制作函数window.polishToEnglish = function(...){},但没有效果。任何想法如何解决这个问题?

标签: javascript

解决方案


简单的解决方案:以正确的顺序链接到它们。所以:

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

因为checkSelection使用来自其他两个文件的声明,并且polishToGerman依赖于polishToEnglish.

(更好的解决方案是使用某种模块,例如 ES6 的export-import或 CommonJS 和module.exports- require)。


推荐阅读