0

I have this code and want to access a class method outside the class in AssetsMap array.

import OrientationEnum from "../enums/orientation_enum";
import * as gameconfig from "../gameconfig";
import GA from "./analytics";
import * as Raven from "raven-js";
import {getQueryString} from "./tools";

const AssetsMap = new Map([
    [AssetsEnum.background, 'common/background.jpg']
]);

class AssetsManager {

    constructor...

    getConfigValue(key, defaultValue) { ... }

}

if I try to access getConfigValue method inside map array somethings like this

[AssetsEnum.background, 'common/background'+this.getConfigValue()+'.jpg']

the console throws error that getConfigValue is not defined. How should I access the method?

1
  • Why don't you declare AssetsMap inside constructor? Commented Feb 20, 2020 at 10:25

2 Answers 2

1

To be able to access a class method, you will need to have a reference to the class instance. E.g.

import OrientationEnum from "../enums/orientation_enum";
import * as gameconfig from "../gameconfig";
import GA from "./analytics";
import * as Raven from "raven-js";
import {getQueryString} from "./tools";

class AssetsManager {

    constructor...

    getConfigValue(key, defaultValue) { ... }

}

const manager = new AssetsManager();

const AssetsMap = new Map([
    [AssetsEnum.background, 'common/background' + manager.getConfigValue() + '.jpg']
]);

If the getConfigValue method doesn't use properties from the AssetsManager class, you could also make the method static. Then it will become possible to use this method without having an instance of the class.

import OrientationEnum from "../enums/orientation_enum";
import * as gameconfig from "../gameconfig";
import GA from "./analytics";
import * as Raven from "raven-js";
import {getQueryString} from "./tools";

const AssetsMap = new Map([
    [AssetsEnum.background, 'common/background' + AssetsManager.getConfigValue() + '.jpg']
]);

class AssetsManager {

    constructor...

    static getConfigValue(key, defaultValue) { ... }

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

2 Comments

well i get AssetsManager is not a constructor error when trying to create an object with const manager = new AssetsManager();
Is AssetsManager defined or imported where you are instantiating the class?
0

You can't access the getConfigValue() method outside the class with this keyword. Try putting your Map inside the class.

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.