[英]Is it possible to write a function which dynamically operates on a global variable given it's name as a string parameter to a function?
Is it possible to pass a string which names a global variable to a function which in turn operates on that variable in the global context? 是否可以将一个命名全局变量的字符串传递给一个函数,该函数又在全局上下文中对该变量进行操作?
Sample function: 样例功能:
// the parameter str may be a global like: `"localStorage"`, `"sessionStorage"`.
function (str, key, value){
// the `converted_str` means the `localStorage` or `sessionStorage`
converted_str.setItem(key, value)
}
EDIT-1 编辑1
How about other case, such as this
or not window global variable? 其他情况如何,例如
this
窗口全局变量与否?
If by system variable you mean global variable (which it appears you do), then yes: 如果按系统变量来表示全局变量(看起来确实如此),那么可以:
function (str, key, value){
window[str].setItem(key, value)
}
In a browser, global variables are members of the global window
object, and can be accessed dynamically through that object. 在浏览器中,全局变量是全局的成员
window
对象,并且可以通过该对象动态访问。
For non-globals: 对于非全局变量:
If it is a member of the current this
object, you can use: 如果它是当前的一员
this
对象,你可以使用:
something.method = function (str, key, value){
this[str].setItem(key, value)
};
Alternately, if you just have some variables you want to access dynamically, just put them in your own object. 或者,如果只有一些要动态访问的变量,只需将它们放在自己的对象中即可。
var obj = {
'something': function() {}
};
var str = 'something';
obj[str]();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.