[英]How do I call function with changing name properly in 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");
}
结果:
类型错误:位置不是 function
如您所见,我想使用保存到数据库的 user.currentLoc 信息(城镇名称)调用 function。 但似乎我无法将它添加到变量中并使用它。 我在这里想念什么? 调用 function 时是否输入错误? 我很确定有一些简单的解决方案可以解决这个问题,但即使几个小时后我仍然无法正确地做到这一点。
您正在尝试访问Locations
object 的属性字段。 This field is a function, however, if you are trying to call this function by the name of a variable, the Javascript interpreter will take it as a direct call of the function.
let manager = {
setStart: () => {
const currentLocation = user.currentLoc;
// Access the Locations property
const fn = Locations[currentLocation];
// Invoke the function
fn(`load`);
}
};
希望能帮助到你。
也许Locations[currentLocation]('load')
是你的意思,但都是一样的 - 看起来 Locations 不在你的 Manager 文件的 scope 中,你需要以某种方式导入它。 根据您的项目,这可能是缺少的require
或import
let manager = {
setStart: () => {
const currentLocation = user.currentLoc;
// Access the Locations property
const fn = Locations[currentLocation];
// Invoke the function
fn(`load`);
}
};
这做到了。 谢谢 VRoxa。 我不知道 Javascript 是这样工作的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.