简体   繁体   English

给定名称作为函数的字符串参数,是否可以编写一个对全局变量动态操作的函数?

[英]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.

相关问题 coffeescript / bone.js:编写对字符串进行操作的哈希函数 - coffeescript / backbone.js: write a hash function that operates on a string 调用其名称类似于给定字符串的函数 - call a function that it's name is like a given string 如果函数采用与全局(同名)变量重叠的参数会发生什么? - What happens if a function takes a parameter that overlaps with a global (same name) variable? 获取作为函数参数的变量名作为字符串 - getting variable name which is a argument of the function as a string 将全局变量分配给功能参数 - Assign Global Variable to Function Parameter 操作全局变量作为函数中的参数 - Manipulate global variable as parameter in function 当 function 的 scope 具有相同名称时,是否可以不否决全局变量? - Is it possible to not overrule a global variable in the scope of a function, when it has the same name? 是否可以获得正在运行给定闭包的 function 名称? - is it possible to get function name in which given closure is running? 是否可以在不使用中间全局变量的情况下访问封闭函数的this或其他变量? - Is it possible to access enclosing function's this or other variable without intermediate global? 在 JavaScript 中通过名称字符串动态获取全局变量 - Get global variable dynamically by name string in JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM