Take this factory function:
function factory(){
return factory_level2(){
return function complexCode{ // <= Code of interest
//...
}
}
}
const lvl2 = factory()
lvl2();
Does the manufactured function complexCode get instantiated every time the above code is called? Or is the compiler smart enough to know to optimize it into something like this:
function complexCode{
//...
}
function factory(){
return factory_level2(){
return complexCode // Returns reference rather than instantiates?
}
}
The compiler generally cannot and should not optimize the code into your second example. The reason for this is because the scope of the two code are different - meaning they have different closures.
All modern javascript engine in common use (Spidermonkey, Squirrelfish and V8) will compile the instructions of the functions only once. So if this is what you are asking then yes. They are compiled only once and all calls to them will share the same bytecodes.
However, you used the word "instantiation". In OO languages, a class is normally only compiled once. Just like the description of how functions are compiled in javascript above. However, a class can be instantiated into many objects. All objects belonging to the same class will share the same executable code. However they don't share the memory of the variables they use (properties they have). All variables/properties are unique to each object.
The following is an example of OO in a fictional programming language:
class A {
property i;
property j;
method foo () {
print( i+j );
}
}
variable x = new A();
variable y = new B();
x.i = 1;
x.j = 2;
y.i = 10;
y.j = 20;
x.foo(); // should print 3 instead of 30
// because x and y don't share the
// same memory
print( addressof x.foo == addressof y.foo ); // should print true
// because both "foo"
// are actually the same
Javascript functions make the same optimization. In your example factory and factory_level2 and complexCode will be compiled only once. Every call to them will execute code from the same memory address. However, each call will instantiate its own scope - the instance of the scope is the closure.
In most programming languages the behavior of function calls work the same but normally you don't need the concept of closures in some languages because they cannot return functions. Due to the fact that javascript can return a function the scope is instantiated and saved for future use - this long-term instantiation of scope is called a closure. In languages that cannot return functions the temporary activation of scope is called an activation record or also commonly known as the stack frame. The difference between a closure an a stack frame is that the stack frame is deleted at the end of the function call. In languages like javascript the runtime needs to check if the variable in the stack frame is linked to a returned function. If it is then it cannot be deleted because that function may be called in the future. It is thus saved as a closure.
The following is an example in another fictional language:
function A () {
variable i = 0;
return function () {
i++;
print(i);
}
}
variable x = A();
variable y = A();
print( addressof x == addressof y ); // should print true
x(); // prints 1
x(); // prints 2
y(); // prints 1 because even though x and y share the same
// function they don't share the variable i which is
// captured in a closure
Note that all the examples above are in a made up language to illustrate what I'm describing because certain things are difficult or impossible to demonstrate in javascript (such as getting the memory address of a function). However the concepts are true for most modern implementations of javascript (or indeed any implementation of javascript that has had enough pressure to be optimized)
This is technically implementation-dependent. But any decent implementation will only compile the function once and reuse that.
If complexCode() is a closure (i.e. it references variables that are declared in factory() or factory_level2(), all the closure instances will reference the same code object, with different environment objects that contain the variable bindings for that instance.
This is similar to the way class methods are assigned once to the prototype object and reused by all the instances.
Related
Let me ask one question. It's about closures in JavaScript, but not about how they work.
David Flanagan in his "JavaScript The Definitive Guide 6th Edition" wrote:
...Technically, all JavaScript functions are closures: they are objects, and they have a scope chain associated with them....
Is this correct? Can I call every function (function object + it's scope) a "closure"?
And stacks' tag "closures" says:
A closure is a first-class function that refers to (closes over) variables from the scope in which it was defined. If the closure still exists after its defining scope ends, the variables it closes over will continue to exist as well.
In JavaScript every function refers to variables from the scope in which it was defined. So, It's still valid.
The question is: why do so many developers think otherwise? Is there something wrong with this theory? Can't it be used as general definition?
Technically, all functions are closures. But if the function doesn't reference any free variables, the environment of the closure is empty. The distinction between function and closure is only interesting if there are closed variables that need to be saved along with the function code. So it's common to refer to functions that don't access any free variables as functions, and those that do as closures, so that you know about this distinction.
It's a tricky term to pin down. A function that's simply declared is just a function. What makes a closure is calling the function. By calling a function, space is allocated for the parameters passed and for local variables declared.
If a function simply returns some value, and that value is just something simple (like, nothing at all, or just a number or a string), then the closure goes away and there's really nothing interesting about it. However, if some references to parameters or local variables (which, mostly, are the same) "escape" the function, then the closure — that space allocated for local variables, along with the chain of parent spaces — sticks around.
Here's a way that some references could "escape" from a function:
function escape(x, y) {
return {
x: x,
y: y,
sum: function() { return x + y; }
};
}
var foo = escape(10, 20);
alert(foo.sum()); // 30
That object returned from the function and saved in "foo" will maintain references to those two parameters. Here's a more interesting example:
function counter(start, increment) {
var current = start;
return function() {
var returnValue = current;
current += increment;
return returnValue;
};
}
var evenNumbers = counter(0, 2);
alert(evenNumbers()); // 0
alert(evenNumbers()); // 2
alert(evenNumbers()); // 4
In that one, the returned value is itself a function. That function involves code that makes reference to the parameter "increment" and a local variable, "current".
I would take some issue with conflating the concept of a closure and the concept of functions being first-class objects. Those two things really are separate, though they're synergistic.
As a caveat, I'm not a formalist by basic personality and I'm really awful with terminology so this should probably be showered with downvotes.
I would try to answer your question knowing you were asked about what closures are during the interview (read it from the comments above).
First, I think you should be more specific with "think otherwise". How exactly?
Probably we can say something about this noop function's closure:
function() {}
But it seems it has no sense since there are no variables would bound on it's scope.
I think even this example is also not very good to consider:
function closureDemo() {
var localVar = true;
}
closureDemo();
Since its variable would be freed as there is no possibility to access it after this function call, so there is no difference between JavaScript and let's say C language.
Once again, since you said you have asked about what closures are on the interview, I suppose it would be much better to show the example where you can access some local variables via an external function you get after closureDemo() call, first. Like
function closureDemo() {
var localVar = true;
window.externalFunc = function() {
localVar = !localVar; // this local variable is still alive
console.log(localVar); // despite function has been already run,
// that is it was closed over the scope
}
}
closureDemo();
externalFunc();
externalFunc();
Then to comment about other cases and then derive the most common definition as it more likely to get the interviewer to agree with you rather than to quote Flanagan and instantly try to find the page where you've read it as a better proof of your statement or something.
Probably your interviewer just thought you don't actually know about what closures are and just read the definition from the book. Anyhow I wish you good luck next time.
The definition is correct.
The closure keeps the scope where it was born
Consider this simple code:
getLabelPrinter = function( label) {
var labelPrinter = function( value) {
document.write(label+": "+value);
}
return labelPrinter; // this returns a function
}
priceLabelPrinter = getLabelPrinter('The price is');
quantityLabelPrinter = getLabelPrinter('The quantity is');
priceLabelPrinter(100);
quantityLabelPrinter(200);
//output:
//The price is: 100 The quantity is: 200
https://jsfiddle.net/twqgeyuq/
I've seen experts using below to declare a function:
(function () {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
//etc
}());
e.g.
https://github.com/douglascrockford/JSON-js/blob/master/json.js
Could someone help me understand when should we use above pattern and how do we make use of it?
Thanks.
Well, since ECMA6 hasn't arrived yet, functions are about the best way to create scopes in JS. If you wrap a variable declaration of sorts in an IIFE (Immediately Invoked Function Expression), that variable will not be created globally. Same goes for function declarations.
If you're given the seemingly daunting task of clearing a script of all global variables, all you need to do is wrap the entire script in a simple (function(){/*script here*/}());, and no globals are created, lest they are implied globals, but that's just a lazy fix. This pattern is sooo much more powerful.
I have explained the use of IIFE in more detail both here, here and here
The basic JS function call live-cycle sort of works like this:
f();//call function
||
====> inside function, some vars are created, along with the arguments object
These reside in an internal scope object
==> function returns, scope object (all vars and args) are GC'ed
Like all objects in JS, an object is flagged for GC (Garbage Collection) as soon as that object is not referenced anymore. But consider the following:
var foo = (function()
{
var localFoo = {bar:undefined};
return function(get, set)
{
if (set === undefined)
{
return localFoo[get];
}
return (localFoo[get] = set);
}
}());
When the IIFE returns, foo is assigned its return value, which is another function. Now localFoo was declared in the scope of the IIFE, and there is no way to get to that object directly. At first glance you might expect localFoo to be GC'ed.
But hold on, the function that is being returned (and assigned to foo still references that object, so it can't be gc'ed. In other words: the scope object outlives the function call, and a closure is created.
The localFoo object, then, will not be GC'ed until the variable foo either goes out of scope or is reassigned another value and all references to the returned function are lost.
Take a look at one of the linked answers (the one with the diagrams), In that answer there's a link to an article, from where I stole the images I used. That should clear things up for you, if this hasn't already.
An IIFE can return nothing, but expose its scope regardless:
var foo = {};
(function(obj)
{
//obj references foo here
var localFoo = {};
obj.property = 'I am set in a different scope';
obj.getLocal = function()
{
return localFoo;
};
}(foo));
This IIFE returns nothing (implied undefined), yet console.log(foo.getLocal()) will log the empty object literal. foo itself will also be assigned property. But wait, I can do you one better. Assume foo has been passed through the code above once over:
var bar = foo.getLocal();
bar.newProperty = 'I was added using the bar reference';
bar.getLocal = function()
{
return this;
};
console.log(foo.getLocal().newProperty === bar.newProperty);
console.log(bar ==== foo.getLocal());
console.log(bar.getLocal() === foo.getLocal().getLocal());
//and so on
What will this log? Indeed, it'll log true time and time again. Objects are never copied in JS, their references are copied, but the object is always the same. Change it once in some scope, and those changes will be shared across all references (logically).
This is just to show you that closures can be difficult to get your head round at first, but this also shows how powerful they can be: you can pass an object through various IIFE's, each time setting a new method that has access to its own, unique scope that other methdods can't get to.
Note
Closers aren't all that easy for the JS engines to Garbage Collect, but lately, that's not that big of an issue anymore.
Also take your time to google these terms:
the module pattern in JavaScript Some reasons WHY we use it
closures in JavaScript Second hit
JavaScript function scope First hit
JavaScript function context The dreaded this reference
IIFE's can be named functions, too, but then the only place where you can reference that function is inside that function's scope:
(function init (obj)
{
//obj references foo here
var localFoo = {};
obj.property = 'I am set in a different scope';
obj.getLocal = function()
{
return localFoo;
};
if (!this.wrap)
{//only assign wrap if wrap/init wasn't called from a wrapped object (IE foo)
obj.wrap = init;
}
}(foo));
var fooLocal = foo.getLocal();
//assign all but factory methods to fooLocal:
foo.wrap(fooLocal);
console.log(fooLocal.getLocal());//circular reference, though
console.log(init);//undefined, the function name is not global, because it's an expression
This is just a basic example of how you can usre closures to create wrapper objects...
Well the above pattern is called the immediate function. This function do 3 things:-
The result of this code is an expression that does all of the following in a single statement:
Creates a function instance
Executes the function
Discards the function (as there are no longer any references to it after the statement
has ended)
This is used by the JS developers for creating a variables and functions without polluting the global space as it creates it's own private scope for vars and functions.
In the above example the function f(){} is in the private scope of the immediate function, you can't invoke this function at global or window scope.
Browser-based JavaScript only has two scopes available: Global and Function. This means that any variables you create are in the global scope or confined to the scope of the function that you are currently in.
Sometimes, often during initialization, you need a bunch of variables that you only need once. Putting them in the global scope isn't appropriate bit you don't want a special function to do it.
Enter, the immediate function. This is a function that is defined and then immediately called. That's what you are seeing in Crockford's (and others') code. It can be anonymous or named, without defeating the purpose of avoiding polluting the global scope because the name of the function will be local to the function body.
It provides a scope for containing your variables without leaving a function lying around. Keeps things clean.
I'm trying to write an application in JavaScript, which I've been using for bits of scripting in web pages for years, and I find my understanding of scope and object orientation is coming up somewhat short. My background is mostly in object oriented languages like C# and Ruby so JavaScript's weird pseudo object-oriented functional approach is confusing me no end.
What I'm having trouble with is this and why I seem to always need it in every reference to anything in my class. It just seems to result in an inordinate amount of typing in order to write much that is useful in JS and I can't help but feel I must be doing it wrong somehow:
function MyClass()
{
var a=1;
this.b = 2;
this.internalMethod= function()
{
console.log("a is: "+a); // returns "a is: 1"
// console.log("b is: "+b); - this fails because b is undefined
console.log("this.a is: "+this.a); // returns "this.a is: undefined" but doesn't crash.
console.log("this.b is: "+this.b); // returns "this.b is: 2"
}
}
MyClass.prototype.externalMethod = function()
{
// console.log("a is: "+a); - fails
// console.log("b is: "+b); - fails
console.log("this.a is: "+this.a); // "this.a is: undefined"
console.log("this.b is: "+this.b); // "this.b is: 2"
}
var m = new MyClass();
m.internalMethod();
m.externalMethod();
What I am understanding from this is that if I am adding a new public method through the class.prototype approach, I only have access to properties that are defined with this.
If I create an internal method in the class definition function I have access to any var values in the class itself and I can access this.property as long as I include the this.
Is this correct? Do I always have to include an explicit object reference to access properties in any functions that use the prototype method? If so, should I be declaring all my functions within the parent class function rather than using the class.prototype pattern for adding them?
In essence I am looking for a standard approach to managing variable scope when writing object oriented Javascript. Most of the articles I can find on this topic are either basic introductions to object orientation or seem to gloss over this area. A lot of my classes are fairly data intensive and having to make calls in the form this.myMethod( this.firstArray, this.secondArray, this.thirdArray, this.fourthArray ) seems like a long cut and impedes the readability of code.
(I am aware of the var that=this trick for avoiding caller scope problems but I didn't want to mess up my examples with it as as far as I know it's not really pertinent to my question.)
function MyClass()
{
var a=1;
this.b = 2;
this.internalMethod= function()
{
console.log("a is: "+a); // returns "a is: 1"
// console.log("b is: "+b); - this fails because b is undefined
console.log("this.a is: "+this.a); // returns "this.a is: undefined" but doesn't crash.
console.log("this.b is: "+this.b); // returns "this.b is: 2"
}
}
In that code, the first console.log will return the right value, because you declared the variable a and then declared the function, which grabs it's environment and saves it all into something called closure (this explanation might be a bit off), so what happens here, is that when you call internalMethod, that function in it's environment also has the definition of a. Which might be confusing, because when you do your second console.log your see "undefined", which is because the a variable is not an attribute of this, but rather just a global variable to the scope of your internalMethod.
MyClass.prototype.externalMethod = function()
{
// console.log("a is: "+a); - fails
// console.log("b is: "+b); - fails
console.log("this.a is: "+this.a); // "this.a is: undefined"
console.log("this.b is: "+this.b); // "this.b is: 2"
}
In that code, a is not defined, becuase it didn't exist when you declared your method, but this.b does, because is part of the attributes of MyClass, which is what you're working on.
So, to summarize, you'll want to use the this keyword when adding or using internal attributes to your "class" (which you should not call class, since that doesn't exists here). It might be a pain, but it's the only way to reference internal attributes of your objects from within it's methods.
Additionally, you might find these two articles interesting to read, since they explain a bit about OOP techniques for JS and some common mistakes:
http://www.commented-out.com/2012/06/12/javascript-oop-for-the-uninitiaded/
http://www.commented-out.com/2012/05/28/javascript-youre-doing-it-wrong/
Let me know if you have more questions.
What I am understanding from this is that if I am adding a new public method through the class.prototype approach, I only have access to properties that are defined with this.
If I create an internal method in the class definition function I have access to any var values in the class itself and I can access this.property as long as I include the this.
There are no such things as "internal" and "external" properties, only "own" and "inherited" properties. In your example, internalMethod is directly assigned to the new object, while externalMethod is inherited from the prototype. They are not different or special in any way. Any two functions that are defined in different scopes are always different.
internalMethod has access to the local variables in the constructor because it is a closure.
Do I always have to include an explicit object reference to access properties in any functions that use the prototype method?
It's important to understand that there is no implicit connection between functions and the objects "they are assigned" to. Functions are independent entities.
The connection is only determined at runtime, by setting this accordingly. So yes, you will need this, for every function, not only those assigned to the prototype. Learn more about this.
If so, should I be declaring all my functions within the parent class function rather than using the class.prototype pattern for adding them?
This is extensively discussed here:
Declaring javascript object method in constructor function vs. in prototype
Use of 'prototype' vs. 'this' in JavaScript?
In essence I am looking for a standard approach to managing variable scope when writing object oriented Javascript.
My subjective advice:
Keep it simple. Don't try to simulate private variables/methods through local variables and closures. Initialize and assign instance-specific data in the constructor, and assign anything that should be shared between instances (such as methods) to the prototype. Use a naming convention, such as this.privateProperty_ to indicate properties that should be accessed by external code.
A lot of my classes are fairly data intensive and having to make calls in the form this.myMethod( this.firstArray, this.secondArray, this.thirdArray, this.fourthArray ) seems like a long cut and impedes the readability of code.
In this example, this inside myMethod will refer to the object itself, so you can access this.firstArray, this.secondArray, etc, just in like that inside the function. You don
t have to pass them.
JavaScript doesn't look up variables in an object, because it's not a classical inheritance language. It's more based on Scheme, with its lexical scope.
Your examples show 2 things:
this refers to the object being instantiated
a is just a variable
In the internalMethod, you're still in the constructor function. So you have access to the variables defined in the constructor (function scope and lexical scope). However, once you get out of the constructor, a is not reachable anymore.
this.b means that on the instantiated object, you attach the property b. It's basically the equivalent of this:
function Foo() {}
var foo = {
b: ''
};
foo.constructor.prototype = Foo.prototype;
Basically. Instantiating with new does a little bit more.
So if you want to access the instantiated object, you have to use this. If you just want to use the power of lexical scope, you can also play with simple variables and closures.
For example, this constructor will instantiate a new object every time it's called, and there is no this:
function Foo() {
var a = 1;
var b = 2;
return {
internalMethod: function() {
return a;
},
incB: function() {
return ++b;
}
};
}
var foo = Foo();
foo.internalMethod(); // 1
foo.incB(); // 3
foo.incB(); // 4
var bar = new Foo();
bar.incB(); // 3
This pattern is called the "module pattern".
If you find limiting the use of an object, you can return an object by using a immediately-executed function (and thus having another scope to play with):
function Foo() {
var a = 1;
var b = 2;
return function() {
var c = 3;
return {
a: a,
c: c
};
}();
}
I seem to always need it in every reference to anything in my class. It just seems to result in an inordinate amount of typing in order to write much that is useful in JS
You're not doing it wrong. In my comment I referenced this answer where I try to explain every stage of writing a constructor, after reading it you'll understand why it's not wrong to use this, however, JavaScript does provide another statement, with that you could use to reduce how much you need to type after a property is initialised.
function MyConstructor() {
this.a = 1; // initialise properties with `this`
this.b = 2;
this.c = 3;
this.d = 4;
}
MyConstructor.prototype = {};
MyConstructor.prototype.foobar = function() {
var c = 5, e = null;
with (this) { // `with` now means you can do `a` instead of `this.a`
var d = 6;
console.log(a, b, c, d, e);
a = 0 - a; // in `this`, property gets set to property
b = -2; // in `this`
c = -c; // in `this`, var'd outside `with`, property gets set to property
d = -d; // in `this`, var'd inside `with`, property gets set to var
e = 100; // not in `this`, var'd, var gets set (not var'd => global set)
}
};
x = new MyConstructor(); // new instance
console.log(x.a, x.b, x.c, x.d, x.e);
// 1 2 3 4 undefined -- undefined as no property `e`
x.foobar();
// 1 2 3 6 null -- 6 from var, null from `var e = null`
console.log(x.a, x.b, x.c, x.d, x.e);
// -1 -2 -3 -6 undefined -- undefined as still no property `e`
I suggest reading about the Javascript module pattern to learn about public / local attributes and scope.
var declares a variable that will be accessible in the current function and the inner ones.
Any method / attribute attached to an object is said "public" as it can be accessed from anywhere.
Local variables, 'trapped' in closures, are used to emulate private members.
Attaching public methods to the prototype is the best memory-efficient approach to reuse those methods on different instances. You could use closures as well in those prototype methods.
One thing to note: as closures emulate 'private' variables but not 'protected' ones, it makes inheritance quite tricky when you need it.
Whats the main purpose of Closures in JS. Is it just used for public and private variables? or is there something else that I missed. I am trying to understand closure and really want to know what are the main advantages of using it.
Closures have to do with how javascript is scoped. To say it another way, because of the scoping choices (i.e. lexical scoping) the javascript designers made, closures are possible.
The advantage of closures in javascript is that it allows you to bind a variable to an execution context.
var closedIn = {};
var f = function(){
closedIn.blah = 'blah'; // closedIn was just "closed in" because I used in the function, but it was defined outside the function.
}
in that example, you have a normal object literal called closedIn. It is accessed in a function. Because of that, javascript knows it has to bring closedIn everywhere it brings the function f, so it is available to f.
The this keyword is tricky. this is always a reference to the execution scope. You can capture the this of one context to use in another context as follows:
var that = this;
var f = function(){
that.somethingOnThat();
// `this` means the scope f, `that` means whatever 'this' was when defined outside of the function
}
This trick can be very useful somethings, if you are coding object oriented javascript and want a callback to have access to some external scope.
To quote from a Javascript book:
"Functions in JavaScript are lexically
rather than dynamically scoped. This
means that they run in the scope in
which they are defined, not the scopee
from which they are executed. When a
function is defined, the current scope
chain is saved and becomes part of the
internal state of the function."
So the clear advantage is that you can bring any object (functions, objects, etc) along with the scope chain as far as is necessary. This is can also be considered a risk, because your apps can easily consume lots of memory if you are not careful.
I think the best phrase to sum up the purpose of closures would be:
Data Encapsulation
With a function closure you can store data in a separate scope, and share it only where necessary.
If you wanted to emulate private static variables, you could define a class inside a function, and define the private static vars within the closure:
(function () {
var foo;
foo = 0;
function MyClass() {
foo += 1;
}
MyClass.prototype = {
howMany: function () {
return foo;
}
};
window.MyClass = MyClass;
}());
Closures are necessary in javascript due to the fact that most API's that require callback functions (for instance, an "onclick" function) do not provide other mechanisms to send parameters to those callback functions (or to explicitly set the "this" pointer). Instead, you need to use closures to allow the callback to access variables in the "parent" function.
I personally wish that they weren't necessary, since they can be hard to understand, make for hard to read code (it's not always clear what exactly is in scope), and make for weird bugs. Instead I wish there was a standard for callbacks that allowed you to send parameters, etc. But I accept that I am in the minority in this view.
As we know, the variables that are defined in functions, have local scope. We can't access them from outside of the function.
Problem 1:
local variables are created when the function is called and they will be destroyed when the function's task is finished. It means local variables have shorter life time than global variables. We may use global variables to overcome that issue.
Global variables are available when the program starts and are destroyed when it ends. They are also available throughout the program.
Problem 2:
Since global variables are accessible throughout the program, they are prone to change from everywhere.
What do we want?
We want to have data persistency + data encapsulation.
We can achieve them by using Closures. By using a closure we can have private variables that are available even after a function's task is finished.
Example:
function initCounter() {
let counter = 0;
return function () {
return ++counter;
}
}
// Each counter is persistent
const countJumps = initCounter();
countJumps();
countJumps();
alert("Jumps count is: " + countJumps());
const countClicks = initCounter();
countClicks();
countClicks();
countClicks();
countClicks();
alert("Clicks count is: " + countClicks());
// Each counter is isolated
alert(counter); // Error: counter is not defined
Here are two samples of js code:
A. function _foo is defined within the global context
function _foo(){ //some code here
}
//... some unrelated code here
var foo = function(){
var result = _foo();
return result;
}
B. function _foo is defined within the function context
var foo = function(){
function _foo(){ //some code here
}
var result = _foo();
return result;
};
Which one of them is a better programming practice in terms of memory management? Since the function foo will be called many times in the application, is it better to keep _foo in the global context (of the app) and not create it within the function context everytime foo is called? Or since _foo will be (mostly) used inside foo, it makes sense to keep it part of the activation object?
C: Caching
var foo = (function(){
function _foo(){ //some code here
}
return function() {
var result = _foo();
return result;
}
}());
Foo is immediately executed and the function _foo is only declared once.
In modern browsers this is 5% slower then a "global" function.
Relevant Benchmark
To answer your question directly, if you're going to have to instantiate an object of foo every time that you want to call it, then declaring it at global scope would certainly be a faster alternative.
However, in JavaScript there will almost certainly be quicker wins from a performance perspective, most often pertaining to DOM interaction.
In these sorts of examples, I would recommend you stick with best programming practice. What would you do if this were C#, Java or some other more strongly-typed language? Well, you wouldn't be able to declare a global function, so you would put it in a class, either as a static method, or as a public method:
var foo = function(){};
//static method
foo._foo = function(){
alert("_foo");
};
//public method
foo.prototype._foo2 = function(){
alert("_foo2");
};
//calling static method
foo._foo();
//instantiating and calling public method:
var f = new foo();
f._foo2();
//note: this won't work (as we would expect!)
foo._foo2();
Most things like this are a trade-off, favouring style and structure here over performance is a good one.
Try an create your functions on the global context and use closure functions as asynchronous callbacks specific to the original functional request. You can potentially get into nasty memory leaks with too many anonymous function calls, because javascript will hold onto the top level variables that you use within the closure.
You may also want to use closure functions if you're trying to design in an OO style for private members. Do some Google/Stackoverflow searches on 'object oriented javascript' and your get more design help on that particular topic.
A quote From MDN:
https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope
Closures can use up a lot of memory. The memory can be freed only when the returned inside is no longer accessible...
Because of this inefficiency, avoid closures whenever possible, i.e. avoid nesting functions whenever possible.
Again, considering OO design is good... wrapping your functions into an object so that you can call them statically or via an object reference is a good design as well.