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?
There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated.
To convert a string in to function "eval()" method should be used. This method takes a string as a parameter and converts it into a function.
The Complete Full-Stack JavaScript Course! Yes, parent and child classes can have a method with the same name.
An alternative to eval is Function() . Just like eval() , Function() takes some expression as a string for execution, except, rather than outputting the result directly, it returns an anonymous function to you that you can call.
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.
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"]();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With