GBeebe Posted August 1, 2014 Share Posted August 1, 2014 How would I get something like this to work?window.onload = function() { var something; outsideFunction(); function insideFunction() { //do stuff }}outsideFunction() is in ai.js, and included by:<script type="text/javascript" src="ai.js"></script>I'm trying to get outsideFunction() to access variables (something) and methods (insideFuncion) inside the window.onload block, but it keeps giving me undefined errors within outsideFuncion(). PS, sorry that it's not "2D" specific, I don't see a general coding forum here. Quote Link to comment Share on other sites More sharing options...
rafinskipg Posted August 1, 2014 Share Posted August 1, 2014 Helloo, good morning. Several things. 1 - In JavaScript, a function search for its variables in his scope, that means that outsideFunction will first search for the variable inside itself, then if it's not found it will look for it on the parent scope (the window onload stuff). The problem, outside function its not defined in the window onload stufff, its called from there, but not defined there, so, when it looks for "var something" it looks on the parent scope where its defined. Solution 1: Use parameters.var something;function outSideFunction(something){ var result = getCalculatedStuff(something); return result;}Passing parameters to functions is "correct", better than working with global stuff. It's more correct even if you dont modify the passed parameters, instead return the result of the calculus , but not over the passed object. In JavaScript all are objects, that means they share the reference, so whenever you pass a object as a parameter and modify it, it gets directly modified in the declaration of the object. And it's better to try to avoid that in some cases, for better code. About the "insideFunction", don't do that, define your functions normally outside the window.onload, then you can call it. It's happening the same, the outsideFunction doesn't find the insideFunction name. 2 - This is not 2D specific, it's more the kind of question for "Stackoverflow" but i liked to reply Quote Link to comment Share on other sites More sharing options...
PAEz Posted August 2, 2014 Share Posted August 2, 2014 Incase you missed it what you need to know is Scope and Closures, this is really important js fundamentals.Heres a few links on the subject that looked ok....http://doctrina.org/JavaScript:Why-Understanding-Scope-And-Closures-Matter.htmlhttp://ryanmorr.com/understanding-scope-and-context-in-javascript/http://speakingjs.com/es5/ch01.html#basic_var_scope_and_closures Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.