www.webdeveloper.com
Results 1 to 7 of 7

Thread: [RESOLVED] call function from a var output

  1. #1
    Join Date
    Jul 2013
    Posts
    21

    resolved [RESOLVED] call function from a var output

    is there any way to store a function call in a var ? if so i could save a 100s of lines in my code

    function heads(){
    document.write("heads")
    }
    function tails(){
    document.write("tails")
    }
    function banana(){
    document.write("banana")
    }
    function apple(){
    document.write("apple")
    }

    if (choice == 1){
    var A = apple()
    var B = banana()
    }
    if (choice == 2){
    var A = heads()
    var B = tails()
    }

    Dice = Math.ceil (Dice * 2)

    if (Dice == 1){
    A
    }
    else if (Dice == 2){
    B
    }

    the point with this is i can just change what A and B = and reuse the "if Dice" otherwise i need to make an "if" for every time i want to run it with different thing
    Disclaimer i know with only 2 vars there is not much point to this but any more and the script will be samaller by doing this

  2. #2
    Join Date
    Jul 2013
    Posts
    16
    No. When you set a variable to a function, the variable stores whatever that function returns. If the function does not return anything, the variable is set to null.

  3. #3
    Join Date
    Jul 2013
    Posts
    21
    so there is no way to even do something like this ?

  4. #4
    Join Date
    Jul 2013
    Posts
    16
    There is no way to set a function to a variable, but you can have the function return something.
    Code:
    function apple(){ return "apple"; }
    var A = apple(); //A is set to apple
    document.write(A);
    I guess the simple answer is I'm sure there are ways to simplify your code, but there isn't a way to set a function call to a variable.

  5. #5
    Join Date
    Mar 2011
    Posts
    60
    A variable can be a reference to a function, which can be used to invoke the referred function.
    Code:
    function heads(){
     document.write("heads");
    };
    
    var f = heads;
    f()

  6. #6
    Join Date
    Jul 2013
    Posts
    16
    Kever is right. Don't know how I missed that. Still not sure that's the best way to simplify your code, but whatever works I guess.

  7. #7
    Join Date
    Jul 2013
    Posts
    21
    it works this will cut down on a LOT
    i am making a text adventure

    my text adventure V0.18 (at the time of this post) now with a basic gui (Manuel stats gen and help pages coming soon prob tomorrow)
    http://www.red566.nf/GuiTest/testlayout.html
    only works with firefox and chrome
    the game ends after the first battle but more coming soon

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles