Simon Trichereau
Simon Trichereau

Reputation: 809

Javascript : use string to invoke function

My question is quite simple. In Php you can call a function including a string in the name of your function. Example :

function setName(name){
    $this->name = name;
}

$string = 'Name';
$method = 'set'.$string;
if(method_exists($this, $method)
    $this->$method($_POST['name']);

So I wanted to know if there was something like this in Javascript... For now, I'm using a switch to check the body id and call the function. This is my code :

switch($('body').attr('id'))
{
    case 'index':
        app.index.init();
        break;
    case 'login':
        app.login.inint();
        break;
};

app.index = {
    init : function(){
        console.log('Hola Mundo');
    }
};

So I was wondering if I could make something like this :

var id = $('body').attr('id');
app.id.init();

thanks for your answers.

Upvotes: 0

Views: 55

Answers (2)

asmmahmud
asmmahmud

Reputation: 5054

It can be done. You don't have to check it in switch. As id attribute is a string value so you can check directly property existence using objectInstance[prop] way and if it exists then you can invoke it safely:

app.index = {
    init : function(){
        console.log('Hola Mundo');
    }
};
app.login = {
    init : function(){
        console.log('Hola Mundo');
    }
};
var appProp = $('body').attr('id'); /* or var id = $('body').id; */
if(app[appProp]){
   app[appProp].init();
}

Upvotes: 0

Manuel Otto
Manuel Otto

Reputation: 6540

Yes.

app[id].init();

But consider that this might cause an error if the id of your body is not defined in the app object, as James already pointed out.

Upvotes: 2

Related Questions