javascript Javascript将字符串转换为函数名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11731211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript convert string into function name
提问by benhowdle89
Possible Duplicate:
Call a JavaScript function name using a string?
javascript string to variable
I have this code:
我有这个代码:
var Functionify = function() {
return {
init: function(el, t) {
var els = document.getElementsByClassName(el);
var elsL = els.length;
while(elsL--){
//els[elsL].onclick = els[elsL].getAttribute(t);
els[elsL].addEventListener('click', els[elsL].getAttribute(t), false);
}
}
};
}();
Where el = 'myClassName'
and t = 'data-id'
哪里el = 'myClassName'
和t = 'data-id'
Now, 't' is a string, how can tell the addEventListener function to use 't' (a string) as a function name?
现在,'t' 是一个字符串,如何告诉 addEventListener 函数使用 't'(一个字符串)作为函数名?
回答by dqhendricks
In the global namespace, you would do something like:
在全局命名空间中,您将执行以下操作:
this.test = function() {
alert('test');
}
window['test']();
The better option however would be to make your function a method of an object you create rather than of the global window
object.
然而,更好的选择是让您的函数成为您创建的对象的方法,而不是全局window
对象的方法。
回答by Joe Johnson
Using eval() is considered "evil", especially in the example given by Danila -- any piece of JS will / can be executed within an eval(). The best option as stated by epascarello, is to use square-bracket notation to invoke a named function. It should be noted, however, that windowt will invoke a function in the global namespace -- if the function is the method of an object, you should reference it as such.
使用 eval() 被认为是“邪恶的”,尤其是在 Danila 给出的例子中——任何一段 JS 都可以/可以在 eval() 中执行。epascarello 所述的最佳选择是使用方括号表示法来调用命名函数。然而,应该注意的是,windowt 将调用全局命名空间中的一个函数——如果该函数是一个对象的方法,你应该这样引用它。
回答by epascarello
I am not sure why you would do it, put if the function is part of the global scope you can use bracket notation.
我不确定你为什么要这样做,如果函数是全局范围的一部分,你可以使用括号表示法。
window["stringName"]();
回答by epascarello
Use eval() function
使用 eval() 函数
Example:
例子:
a = "alert(1)"
eval(a)