0

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.

1
  • 2
    You could do that, app is an object and you can reference a property by a string held in a variable via app[myVar]. However it's less secure than using a switch with definite function names defined. Commented Aug 10, 2017 at 22:48

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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();
}

1 Comment

Work like a charm! Thanks you a lot! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.