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?
What you do works. This passage of MDN explains why:
So this explains why you can call
firstOnefrom within the Ajax callback.Whether this is good design or not depends completely on what you are trying to achieve. If
firstOneis 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 withinsecondOnethat 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.