5

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?

Community
  • 1
  • 1
benhowdle89
  • 36,900
  • 69
  • 202
  • 331

4 Answers4

7

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.

dqhendricks
  • 19,030
  • 11
  • 50
  • 83
1

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"]();
epascarello
  • 204,599
  • 20
  • 195
  • 236
1

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.

Joe Johnson
  • 1,814
  • 16
  • 20
0

Use eval() function

Example:

a = "alert(1)"

eval(a)
  • 1
    this could potentially be dangerous. – dqhendricks Jul 30 '12 at 23:43
  • @dqhendricks: (I know you said "potentially", still...) Only if `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. – Felix Kling Jul 30 '12 at 23:48