javascript - 如何在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 信息(城镇名称)调用函数。但似乎我无法将它添加到变量中并使用它。我在这里想念什么?调用函数时是否输入错误?我很确定有一些简单的解决方案可以解决这个问题,但即使几个小时后我仍然无法正确地做到这一点。
解决方案
您正在尝试访问Locations
对象的属性字段。该字段是一个函数,但是,如果您尝试通过变量名称调用该函数,Javascript 解释器会将其视为函数的直接调用。
let manager = {
setStart: () => {
const currentLocation = user.currentLoc;
// Access the Locations property
const fn = Locations[currentLocation];
// Invoke the function
fn(`load`);
}
};
希望能帮助到你。
推荐阅读
- c# - 使用 Ninject 启动 MVP WinForms 应用程序
- c# - Oxyplot:体积图中的错误缩放比例
- python-2.7 - Google App Engine 中的错误代码 121
- python - 是否可以让 Python 在另一个函数之前读取一个函数?
- react-native - React Native FlatList inside ScrollView onEndReached 从未调用过
- css - SASS Source Map 指向错误的 SASS 文件
- python - 'str' 对象不可调用 - 注意:请勿将特殊函数用作变量
- python-2.7 - 如何在我的 NAO 机器人上写入和记录文件
- elasticsearch - 用于 Elasticsearch 的 URL 编码 cURL 参数
- ruby-on-rails - 如何防止排队延迟作业中的代码在部署后变得无效?