【发布时间】:2019-08-25 11:52:41
【问题描述】:
我的问题是如何访问在其他文件中创建的函数。
我有 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(...){},但没有效果。
任何想法如何解决这个问题?
【问题讨论】:
-
你可以使用模块
export function...然后在第三个import {funcName} from ./path/to/file的顶部 -
engWord是否声明在第三个函数的范围内?如果没有,它将在您分配时插入到全局范围中(window.engWord在浏览器上下文中)。 -
@pmkro 我从来没有使用过模块,所以实现起来有点困难。
-
@jspcal 不,它没有在任何地方声明。但即使在声明之后,也没有任何新的事情发生。
标签: javascript