-3

Can someone explain to me why the second function within the first function is undefined?

var a = 1

function abc () { 
    alert(a); 
        function xyz () { 
            alert(a); 
        } 
}

https://jsfiddle.net/kp950/yLs73cth/

spex5
  • 1,221
  • 4
  • 17
  • 27
  • 1
    You should include your HTML in your question here for it to make sense. – James Thorpe Mar 14 '16 at 12:31
  • 1
    It's not undefined ***inside `abc`.*** It's however not in the *global scope*, somewhat obviously. – deceze Mar 14 '16 at 12:31
  • 1
    Regarding the dupe - inline event handlers in things like `onclick` attributes usually require their targets to be available within the global scope. It's also quite a dated technique - you should look into using [event listeners](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener), which allow you to arbitrarily nest functions and still have them respond to things like button clicks. – James Thorpe Mar 14 '16 at 12:33
  • Refer this for more details: http://stackoverflow.com/questions/8817872/javascript-call-nested-function – Jagrut Mar 14 '16 at 12:34
  • 1
    [updated fiddle](https://jsfiddle.net/yLs73cth/4/) – ozil Mar 14 '16 at 12:35
  • 2
    @ozil _"Uncaught TypeError: abc(...).xyz is not a function"_ - the alert you're seeing is the one from the outer function. You want `onclick="abc()();"` to get it to run the returned function. You get two alerts though, so I'm not sure what this solves. – James Thorpe Mar 14 '16 at 12:36

2 Answers2

1

xyz is an inner function which is private to abc function. You cannot call xyz unless you make it public

brk
  • 48,835
  • 10
  • 56
  • 78
  • It seems like you can though by calling abc().xyz() https://jsfiddle.net/yLs73cth/4/ – spex5 Mar 14 '16 at 12:54
  • @spex5 See my comments under the question related to that - `xyz` isn't actually running there, it's throwing an error. And @user2181397 said "unless you make it public". Returning the inner function from the outer one _is_ making it public. – James Thorpe Mar 14 '16 at 12:57
1

This is due to the scope at which you are trying to execute xyz() (globally). xyz() can only be run inside of abc() - where it is defined in the local scope.

bwegs
  • 3,769
  • 2
  • 30
  • 33