首页 > 解决方案 > 如何在Javascript中正确更改名称来调用函数?

问题描述

所以,这是我目前的问题:

我有 locations.js 文件,其中有几个函数,里面有不同的城镇/地区名称,它们都包含几个开关。这是示例:

let Locations = {

town1: function (eventType) {

    switch (eventType) {
        case "load":
            // Stuff related to main starting point of this location 
            break;

    }}  

他们对其他一切都很好,但现在我试图在启动程序时创建一个“主要访问”。让我们将主文件称为 manager.js

    let Manager = {

    setStart: function () {

       currentLocation = user.currentLoc;

       // Call load function based on current location to start program from right spot
       Locations.currentLocation("load");

}

结果:

TypeError:位置不是函数

如您所见,我想使用保存到数据库的 user.currentLoc 信息(城镇名称)调用函数。但似乎我无法将它添加到变量中并使用它。我在这里想念什么?调用函数时是否输入错误?我很确定有一些简单的解决方案可以解决这个问题,但即使几个小时后我仍然无法正确地做到这一点。

标签: javascriptjavascript-objects

解决方案


您正在尝试访问Locations对象的属性字段。该字段是一个函数,但是,如果您尝试通过变量名称调用该函数,Javascript 解释器会将其视为函数的直接调用。

let manager = {
    setStart: () => {
        const currentLocation = user.currentLoc;

        // Access the Locations property
        const fn = Locations[currentLocation];
        // Invoke the function
        fn(`load`);
    }
};

希望能帮助到你。


推荐阅读