导出的对象无法识别javascript中的函数

时间:2020-07-29 07:36:09

标签: javascript javascript-objects es6-modules es6-class

我有一个使用Js ES6创建的模块。

该模块的函数调用失败,并显示“ dictionary.detectLangDictionary不是函数” 在定义它并且在js主文件中识别出对象的方式,但是在调用-dictionary.detectLangDictionary()

的函数中无法识别出该对象时

我想了解为什么对象没有被识别为对象而函数未被识别。

代码及其结构:

该模块包含4种文件类型:

1。类定义-dictionary.js:

export default class Dictionary
{
    sourceLanguage;
    destinationLanguage;
    dictionary;

    constructor(sourceLanguage,destinationLanguage,dictionary)
    {
        this.sourceLanguage=sourceLanguage;
        this.destinationLanguage=destinationLanguage;
        this.dictionary=dictionary;
    }


    detectLangDictionary(selectionText) {
    ...
    }

    static detectDictionaryFromList(textToDetect,dictionaryList)
    {
        let detectedDictionary=null;
        for (let dictionary in dictionaryList)
        {
            console.log("current dictionary is:",dictionary)
            detectedDictionary=dictionary.detectLangDictionary(textToDetect)
            if (detectedDictionary!=null)
            {
                return detectedDictionary;

            }
        }
        return null;
    }

}

2。创建字典对象并导出它们的文件-englishHebrewDictionary.js和englishRussionDictionary.js等:

import Dictionary from "./dictionary.js";

let dict={
...
} 

export var EnglishHebrewDictionary=new Dictionary("English","Hebrew",dict);
  1. 一个累积导出对象,该对象导出类型2的所有文件-dictionaries.js:

    从“ ./englishHebrewDictionary.js”导出*; 从“ ./englishRussionDictionary.js”导出*; ...

4。调用所有内容的主程序:

import * as dictionaries from "./dictionaries/dictionaries.js"
import Dictionary from "./dictionaries/dictionary.js"
/**
 *detect which dictionary will fit and what the swaped text should contain
 */
function detectLangDictionary(selectionText) {
    console.log("dictionaries value:",dictionaries);
    return Dictionary.detectDictionaryFromList(selectionText,dictionaries);
}

错误:dictionary.detectLangDictionary is not a function

日志结果:

主文件detectLangDictionary函数将字典识别为对象,就像它应该这样:

  dictionaries value () : 
    {
    ​
    EnglishHebrewDictionary: Object { sourceLanguage: "English", destinationLanguage: "Hebrew", dictionary: {…} }
    ​
    EnglishRussionDictionary: Object { sourceLanguage: "English", destinationLanguage: "Russion", dictionary: {…} }
    ​}

被调用且无法识别EnglishHebrewDictionary是对象的静态Directory函数:

current dictionary is: EnglishHebrewDictionary

1 个答案:

答案 0 :(得分:2)

如果我了解您要执行的操作,则字典似乎是一个对象,而不是数组。 for循环遍历属性名称,我认为您需要像这样引用它。

dictionaryList[dictionary].detectLangDictionary(textToDetect)

所以在您的代码中看起来像这样。

static detectDictionaryFromList(textToDetect,dictionaryList)
{
    let detectedDictionary=null;
    for (let dictionary in dictionaryList)
    {
        console.log("current dictionary is:",dictionary)
        detectedDictionary=dictionaryList[dictionary].detectLangDictionary(textToDetect);
        if (detectedDictionary!=null)
        {
            return detectedDictionary;

        }
    }
    return null;
}