Which Javascript placement is better?

I am trying to create a game, and I noticed that for an organization it is better to place some functions inside other functions, because they are used exclusively in the original function. For instance:

function fn1() { fn2(); function fn2() { //Stuff happens here } } 

fn1 is called many times, and fn1 will call fn2 several times in its execution. When fn1 is fn1 , does fn2 need to fn2 processed (due to the lack of a better word) every time? Because of this, am I losing in terms of performance? Should I place fn2 after fn1 instead, like this?

 function fn1() { fn2(); } function fn2() { //Stuff happens here } 
+6
source share
1 answer

You can do this to achieve similar coverage, 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 with their scripts, the first of which creates an additional copy of fn2 , since for each call to fn1 a local area of fn2 : http://jsfiddle.net/A2UvC/3/ and http://jsfiddle.net/A2UvC/3 /

However, there are additional benefits to additional copies of fn2 . They can have access to various variables, for example, in the following situation:

 function fn1(x){ // Return an object exposing fn2 to the caller 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 
+2
source

Source: https://habr.com/ru/post/952527/


All Articles