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?

asked Jul 30, 2012 at 23:39
2
  • I think you mean to say that els[elsL].getAttribute(t) is a string and the name of a variable/function. Otherwise getAttribute(t) would not make sense. Commented Jul 30, 2012 at 23:45
  • @TheEliteNoob: Good duplicate! Commented Jul 30, 2012 at 23:45

4 Answers 4

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.

answered Jul 30, 2012 at 23:48
Sign up to request clarification or add additional context in comments.

Comments

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"]();
answered Jul 30, 2012 at 23:44

Comments

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.

answered Jul 30, 2012 at 23:50

Comments

0

Use eval() function

Example:

a = "alert(1)"
eval(a)
answered Jul 30, 2012 at 23:43

2 Comments

this could potentially be dangerous.
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.