1

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.

1
  • Shouldn't it be Locations.town1("load")? Also, I'm not sure that wrapping these functions in Objects is warranted in your use case. You may be better off just declaring functions within a module. Commented May 12, 2020 at 12:07

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.