Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript convert string into function name [duplicate]

Tags:

javascript

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?

like image 654
benhowdle89 Avatar asked Jul 30 '12 23:07

benhowdle89


People also ask

How can I call a function given its name as a string?

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.

How do I turn a string into a function?

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.

Can two methods have the same name in JavaScript?

The Complete Full-Stack JavaScript Course! Yes, parent and child classes can have a method with the same name.

What is the alternative of eval in JavaScript?

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.


3 Answers

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.

like image 176
dqhendricks Avatar answered Nov 15 '22 08:11

dqhendricks


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"]();
like image 42
epascarello Avatar answered Nov 15 '22 06:11

epascarello


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.

like image 42
Joe Johnson Avatar answered Nov 15 '22 07:11

Joe Johnson