Skip to content

Instantly share code, notes, and snippets.

@rodneyrehm
Created October 29, 2012 11:53
Show Gist options
  • Select an option

  • Save rodneyrehm/3973152 to your computer and use it in GitHub Desktop.

Select an option

Save rodneyrehm/3973152 to your computer and use it in GitHub Desktop.
Javascript: removing nested functions

Avoid Nesting Of Functions

Need a clear statement why: Memory issues, declaration issue, nested functions being "registered" on every invocation of containing function, …

// Function bar() is declared and initialized on every invocation
// of foo(). This takes time, pollutes memory and throws unnecessary
// work in the garbage collector's face
function foo() {
var x = "something";
function bar() {
// use the captured/closured x
alert(x);
}
// run that thing
bar();
}
// Extract nested functions and register them on the function object
// so they may be invoked with any desired context. Functions are
// declared once and don't pollute anything.
function foo() {
var context = {
x: "something"
};
// run that thing
foo.bar.call(context);
}
foo.bar = function() {
alert(this.x);
};
// Use the module pattern to contain functions in a scope that
// is declared once and thus doesn't pollute anything.
var foo = (function() {
var x;
function bar() {
// use the captured/closured x
alert(x);
}
return function() {
// run that thing
x = "something";
bar();
};
})();
@rauschma
Copy link

rauschma commented Nov 4, 2012

I’d opt for the code that is least clever (#1). Have you compared the performance and memory footprint of the alternatives (if the latter is even measurable, for the former you can use jsperf)?

I’d suspect that JavaScript engines internally transform #1 to #2.

Another alternative is obviously to make x a parameter.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment