0

I have this code:

var a = 1;

function test + a() {
    alert('test');    
}

test1();

I've received this error from the browser console:

Uncaught SyntaxError: Unexpected token +

So how can I concatenate the variable a to test which finally run function test1 here?

jsFiddle

user2864740
  • 60,010
  • 15
  • 145
  • 220
user3705773
  • 97
  • 2
  • 8
  • Ref. http://stackoverflow.com/questions/5117127/javascript-dynamic-variable-name , http://stackoverflow.com/questions/11515924/access-javascript-variables-dynamically , http://stackoverflow.com/questions/12826154/can-i-create-dynamic-object-names-in-javascript?lq=1 , http://stackoverflow.com/questions/13291554/dynamic-variables-names-in-javascript – user2864740 Aug 29 '14 at 05:35
  • Simply assign the function to a *given* "dynamic variable name". But better: use an explicit array/object and map the functions to indices/properties. – user2864740 Aug 29 '14 at 05:37

2 Answers2

4

In javascript, all variables/methods declared globally are members of the object window, so you can declare the function this way:

var a = 1;

window['test' + a] = function() {
    alert('test');    
}

test1();

jsFiddle

PS - There are very few situations where you should be doing something like this. If you're unsure, please edit your question. There might be a better way of achieving what you want than using dynamically named functions attached to the global window object. Just because it can be done doesn't mean it should be.

Ayush
  • 41,754
  • 51
  • 164
  • 239
1

Try this :

var a = 1;
var name="test"+a;
var func = new Function(
     "return function " + name + "(){ alert('test');    }"
)();
//function call
func();
Jenz
  • 8,280
  • 7
  • 44
  • 77