I'm trying to build a game and I noticed that for organization it might be better to place some functions inside other functions because they are used in the original function exclusively. For example:
function fn1()
{
fn2();
function fn2()
{
//Stuff happens here
}
}
fn1
gets called many times, and fn1
will call fn2
several times in its execution. When fn1
is called, does fn2
have to be re-processed (for lack of a better word) every time? Am I losing out in terms of performance because of this? Should I place fn2
after fn1
instead, like this?
function fn1()
{
fn2();
}
function fn2()
{
//Stuff happens here
}
JavaScript in head: A JavaScript function is placed inside the head section of an HTML page and the function is invoked when a button is clicked. JavaScript in body: A JavaScript function is placed inside the body section of an HTML page and the function is invoked when a button is clicked.
There is actually no difference at all where you declare the function (it always behaves as if the declaration is on the beginning).
JavaScript functions are essential when writing JavaScript programs if you want to execute a block of code as many times as you want without having to write the same block of code repeatedly in your program. We can simply say the function is a saved algorithm given to a program to work with when called upon.
You can do this to achieve similar scoping, but only create one copy of fn2
:
//Initiliaze before you call `fn1`:
var fn1 = (function(){
// This is the function assigned to fn1
return function(){
fn2();
}
function fn2()
{
//Stuff happens here
}
})();
Compare the console output of these to fiddles, the former of which creates an extra copy of fn2
, since a locally scoped fn2
is created for each call to fn1
: http://jsfiddle.net/A2UvC/3/ and http://jsfiddle.net/A2UvC/3/
There are advantages to the additional copys of fn2
however. They may have access to different variables like in the following situation:
function fn1(x){
// Return an object exposing fn2 to the caller's scope
return {fn2: fn2};
// Each call to fn1 creates a new fn2 which has access
// to the closured `x` from the call to fn1 that created it
function fn2(){
console.log(x);
}
}
var ex1 = fn1(1);
var ex2 = fn1(2);
ex1.fn2 == ex1.fn2; // true
ex1.fn2 == ex2.fn2; // false, because they are two distinct copies
ex1.fn2(); // 1
ex2.fn2(); // 2
ex2.fn2(); // 2
ex1.fn2(); // 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With