Is it ok regarding performance and efficiency to declare a function inside a function that is called on each AnimationFrame? Is A) as ok as B) ?
A)
function update() {
function do () { ...}
}
B)
function update() {
do();
}
function do () { ...}
-
2Why would you declare the function on every frame?tadman– tadman2015年03月31日 15:49:38 +00:00Commented Mar 31, 2015 at 15:49
-
just to closure, what belongs together, sharing same varibalesuser1477955– user14779552015年03月31日 15:51:50 +00:00Commented Mar 31, 2015 at 15:51
-
A and B do not act the same.epascarello– epascarello2015年03月31日 15:54:43 +00:00Commented Mar 31, 2015 at 15:54
2 Answers 2
No, it's not a good idea because you're making it redeclare the same function over and over.
A better pattern would be:
(function() { // this is your closure
var genericVariableOne = 123,
genericVariableTwo = 456;
function genericFunctionOne() {...}
// now do stuff here
})();
This way you are only declaring functions once within the closure. For variables, declaring them outside may or may not be a good idea depending on how they are used.
Comments
Yes - it is ok to declare functions inside functions and in fact desirable in many situations. They are called closures. All major JavaScript APIs depend on this concept heavily from jQuery, to AngularJS to Dojo. Older versions of MSIE discouraged it's use but all modern browsers use JavaScript engines that are very efficient and can give you good performance with closures.