首页 > 解决方案 > Reactjs Access class method outside the class but in same file

问题描述

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?

标签: javascriptreactjsecmascript-6

解决方案


为了能够访问类方法,您将需要对类实例的引用。例如

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']
]);

如果该getConfigValue方法不使用 AssetsManager 类中的属性,您也可以创建该方法static。这样就可以在没有类实例的情况下使用此方法。

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) { ... }

}

推荐阅读