1
var main = {
   doSomething: function(){
      function firstOne(){}
      function secondOne(){
         $.ajax({
            success: function(){
               firstOne(); /* here I want the previous function */
            }
         });
      }
   }
}

How can I run the firstOne() function from the marked line? It's a noobish question perhaps, but I don't get the JS namespace (and I tried).

Is that kind of defining functions good from a JS good practices point of view?

z-x
  • 411
  • 1
  • 6
  • 14

2 Answers2

0

Your code looks OK, and should run fine.

Unlike many other programming languages, Javascript has a scope lookup chain. If a function or variable is not found in the local scope, Javascript will look for it in the scope above that. If it's not found there either, it'll look for it further up in the chain, till it hits the head object (which in a browser would be the window object). If it's not found there, then it throws an error.

Since your firstOne() function is declared in the scope immediately above your AJAX object, Javascript should have no problem finding it for you. There's no need to manually reference the parent scope.

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
0

What you do works. This passage of MDN explains why:

You can nest a function within a function. The nested (inner) function is private to its containing (outer) function. It also forms a closure.

...

Since a nested function is a closure, this means that a nested function can "inherit" the arguments and variables of its containing function. In other words, the inner function contains the scope of the outer function.

To summarize:

The inner function can be accessed only from statements in the outer function.

The inner function forms a closure: the inner function can use the arguments and variables of the outer function, while the outer function cannot use the arguments and variables of the inner function.

So this explains why you can call firstOne from within the Ajax callback.

Whether this is good design or not depends completely on what you are trying to achieve. If firstOne is something that you could reuse in several parts of your code, then it would certainly be a bad decision to define it as a nested function, where it can only be accessed in a local context. But if you had for example two Ajax calls within secondOne that both needed the same functionality in their callback, then it would be a good decision to wrap this in a local nested function. If you just need the behaviour once then it might be overkill (and extra typing) to declare it as a separate function.

Community
  • 1
  • 1
emboss
  • 38,880
  • 7
  • 101
  • 108