Javascript converts a string to a function name

Possible duplicate:
Call JavaScript function name using string?
javascript string for 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 do I tell addEventListener functions to use 't' (string) as the name of the function?

+4
source share
4 answers

In the global namespace, you would do something like:

 this.test = function() { alert('test'); } window['test'](); 

However, the best option would be to make your function a method of the object being created, rather than a global window object.

+7
source

I'm not sure why you will do this, if the function is part of the global scope, you can use parenthesis notation.

 window["stringName"](); 
+1
source

Using eval () is considered "evil", especially in the example given by Danila - any part of JS will / can be executed in eval (). The best option, as stated in epascarello, is to use a square bracket notation to call a named function. It should be noted, however, that windowt will call a function in the global namespace - if the function is a method of an object, you must reference it as such.

+1
source

Use eval () function

Example:

 a = "alert(1)" eval(a) 
0
source

All Articles