我一直看到警告不要在JavaScript中使用全局变量,但似乎人们这么说的唯一原因是因为堵塞了全局命名空间.我可以想象通过将所有变量放入一个大对象中可以很容易地解决这个问题.现在的问题是:除了便利之外,还有其他理由不使用全局变量吗?是否涉及性能或兼容性问题?
我有一个对象,我想使用字符串索引访问该对象值,但是当我尝试在 TypeScript 中执行此操作时,出现错误。
// Declared Globally
const Orientation = {
value: () => 0,
'next_value': () => someFunction.anotherFunction.sqrt(),
};
// _textValue type declared
_textValue : string;
// Declared inside constructor
this._textValue = 'next_value';
// value used inside a function
_getValue(){
const newValue = Orientation[this._textValue]();
}
Run Code Online (Sandbox Code Playgroud)
在我使用的地方Orientation[this._textValue]();
,我收到的错误如下:
元素隐式具有“any”类型,因为“any”类型的表达式不能用于索引类型“{ value: () => number;” '下一个值': () => 数字; }'.ts(7053)
关于如何解决这个问题有什么想法吗?