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'
Now, 't' is a string, how can tell the addEventListener function to use 't' (a string) as a function name?
4 Answers 4
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.
Comments
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"]();
Comments
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.
Comments
Use eval() function
Example:
a = "alert(1)"
eval(a)
2 Comments
a is a string containing JavaScript, received from the server and injected by a malicious user. If you use your own code, it's perfectly fine, although not a very good solution.
els[elsL].getAttribute(t)is a string and the name of a variable/function. OtherwisegetAttribute(t)would not make sense.