0

Can anyone please help me in this? I have declared a function inside a function and now want to call only that function.

For example:

function hello(){
          alert("Hello");

     function insideHello(){
          alert("insideHello");

         }

} 

I just want to call the insideHello function.

I know one way is to call (new hello()).insideHello(); by declaring this.insideHello = function. I don't want to use new every time because I am using this in canvas scenario.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

2 Answers2

2

You could make hello a "module" that exposes insideHello as part of its API:

function hello() {
  alert("Hello");

  function insideHello() {
    alert("insideHello");
  }

  return {
    insideHello // or insideHello: insideHello
  }
}

hello().insideHello()
dfsq
  • 191,768
  • 25
  • 236
  • 258
0

I would have two functions and you call the second one from inside the first - but you can call the second one separately as well (of course the names wont mean much in this example).

function hello(){
   alert("Hello");
   insideHello();
 }


function insideHello(){
    alert("insideHello");
  }

That way you can get both the outer and inner function by calling hello(); and just the inner function by calling insideHello(); ... again noting that the names are not very descriptive since i removed the inner function to the outside. But it seems that if you want to only call the inner one then you shouldn't need to call the outer one. and if you want to call both then the outer one should be able to handle that.

gavgrif
  • 15,194
  • 2
  • 25
  • 27