0

I want to create the name of my function javascript when load in browser and run it.

I want the equivalence of this php's code :

<?php

$name_function = 'toto';

function toto() {
    echo 'toto';
}


$name_function();

?>

My eval : the evil :)

var chaine = 'TabToto';
var store = chaine.substr(3,chaine.length);
eval ('store = this.get'+store+'Store()');

Ok , what i want :

var chaine = 'TabToto';
var store = 'get'+chaine.substr(3,chaine.length)+'Store';

store = this[store]();

My controller create a function to get a store and i want to use it ...

VincentDA
  • 159
  • 1
  • 14

3 Answers3

4
function toto()
{
    alert('toto');
}

var name_function  = 'toto';
window[name_function]();

(assuming this is in global scope)

Eric Hotinger
  • 8,957
  • 5
  • 36
  • 43
3

Instead of providing the name of the function as a string, you can also assign a reference to the function itself to a variable.

That would look like this:

function toto() {
    alert('toto');
}
function toto2() {
    alert('toto 2');
}

var function_to_use = toto;   // notice the lack of quotes
function_to_use();

function_to_use = toto2;
function_to_use();
jcsanyi
  • 8,133
  • 2
  • 29
  • 52
0

i have done like this

function a(){
alert(1);

}
var aa=a;

 aa();
sharif2008
  • 2,716
  • 3
  • 20
  • 34