javascript - 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?
解决方案
为了能够访问类方法,您将需要对类实例的引用。例如
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) { ... }
}
推荐阅读
- ios - 如何防止iOS应用缓存任何数据
- amazon-ec2 - AWS - 通过 kubectl 创建的网络负载均衡器缺少 SSL 证书
- c# - Xamarin 将 ListView 大小(高度)转换为内容?
- python - 直接从 gc.get_objects 中删除对象?
- flutter - 无法在 compute() 函数中使用 http.post
- javascript - jQuery不使用选定的元素
- laravel - Laravel 6 显示白色空白页而不是错误消息
- arrays - 如何根据其索引从数组中提取值
- travis-ci - 如何共享 Travis-CI 中使用的凭据
- cakephp-3.8 - 在查询生成器中创建文本,选择