Reputation: 9
So, this is my current problem:
I have locations.js file that has several functions inside with different town/area names and they all include few switches. This is example:
let Locations = {
town1: function (eventType) {
switch (eventType) {
case "load":
// Stuff related to main starting point of this location
break;
}}
They have been all nice for everything else, but now I'm trying to create a "main access" when starting the program. Let's call main file as 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");
}
Result:
TypeError: Locations is not a function
As you see, I want to call function with user.currentLoc information (town names), which are saved to database. But it seems like I cant add it to variable and just use it. What am I missing here? Do I type it wrong when calling a function? I'm quite sure that there's some easy solution to this, but even after several hours I still fail to do this right.
Upvotes: 1
Views: 184
Reputation: 9
let manager = {
setStart: () => {
const currentLocation = user.currentLoc;
// Access the Locations property
const fn = Locations[currentLocation];
// Invoke the function
fn(`load`);
}
};
This did it! Thanks VRoxa. I had no idea that Javascript works like this.
Upvotes: 0
Reputation: 1051
You are trying to access to a property field of the 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`);
}
};
Hope it helps.
Upvotes: 1
Reputation: 4901
Perhaps Locations[currentLocation]('load')
is what you mean to call, but all the same - it looks like Locations isn't in scope in your Manager file, you need to import it somehow. That could be a missing require
or import
depending on your project
Upvotes: 0