0

I'm having a small issue on running a function inside of a function. Hope u guys can guide me.

<html>
<body>

<p id="demo"></p>

<script>
function myFunction()
{
    function play(a, b)
    {
        document.getElementById("demo").innerHTML = a * b;
    }
}

myFunction().play(2,3);

</script>
</body>
</html>
3
  • 6
    you need to return your inner function play Commented Mar 20, 2018 at 23:53
  • how do i do that Commented Mar 20, 2018 at 23:54
  • 2
    To call like this myFunction().play(2,3); you need to return object that has play method in it. Commented Mar 20, 2018 at 23:55

4 Answers 4

3

To keep with your current usage, try this:

function myFunction()
{
    return {
        play: function(a, b)
        {
            document.getElementById("demo").innerHTML = a * b;
        }
    }
}

myFunction().play(2,3);
Sign up to request clarification or add additional context in comments.

Comments

0

So what you've done with myFunction is nested a 'private' function play inside so the outside cannot call it. So you can either return the inner function or call play inside of function like and only call myFunction:

function myFunction(a, b) {
    function play(a, b) {
        document.getElementById("demo").innerHTML = a * b;
    }
    play(a, b);
}
myFunction(2,3); // will set innerHTML of demo to a*b

Or remove the nesting and just have

function play(a, b) {
  document.getElementById("demo").innerHTML = a * b;
}
play(2,3);

1 Comment

my aim to allow the function play to take values only and i'll be adding numerous other private function in them so this method I think wont be suitable
0

You will not be able to access the play function where you are currently invoking. The play function is out of scope.

function myFunction()
{
    function play(a, b)
    {
        document.getElementById("demo").innerHTML = a * b;
    }

    play(2,3);
}

myFunction()

This should work for you

Comments

0

You can't do this because that function play only exists within the function myFunction and everything outside of it won't be able to execute it.

An alternative is to return an object with a property called play whose value is the function you need to execute.

function myFunction() {
  return {
    play: function(a, b) {
      document.getElementById("demo").innerHTML = a * b;
    }
  }
}

myFunction().play(2, 3);
<p id="demo"></p>

Comments

Your Answer

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