I'll just grab my Web Development notes here:
Yes, nested functions are closures.
With nested functions you have access to variables at definition time (in their scope by lexical context), in contrast to C#, which uses execution context.
The great advantage of using closures is that you still have access to variables after the containing function has ended, through the use of a hidden [[scope]] pointer on the heap.
In JavaScript, if you declare a function within another function, then the local variables can remain accessible after returning the function you called.
http://stackoverflow.com/questions/111102/how-do-javascript-closures-workThere is no class keyword in Javascript, but you can do the following:
function AnObject(){
}
var my = new AnObject();
my.name = "John";
my.definition = function { ... }
The problem with the above approach is that the object properties 'name' and 'definition' (arbitrarily chosen) have only been defined for instance 'my'.
var yours = new AnObject();
alert(yours.name) // returns UNDEFINED
Solutions to this problem:
- Constructor function
- Prototype
Constructor function: you have to use the
this keyword to define public variables and functions (and to define private ones, you use the var keyword)
Prototype:
To add properties and methods to all instances of an object, outside of the constructor. We use the prototype property for this and every object has it.
Javascript is not a real OO language because it's missing the following features:
- namespaces, encapsulation, interfaces, inheritance
What can we do about that? We can imitate these by making specific coding agreements:
use of scope, context and closures.
Namespaces:
You use the object literal notation as a singleton so that you can emulate namespaces.
Encapsulation:
Use naming conventions such as prefixing all private members with an underscore.
Also via closures:
- constructor defines private attributes through the var keyword
- constructor defines privileged methods through the this keyword
- public methods without access to private attributes through prototype keyword
Interfaces through duck typing.
In summary:
- Use the first code example to emulate namespaces so that you have unobtrusive code
- Use the third example to have more flexible code
If your platform is resource-poor, try to consider efficient memory and CPU pipeline use of the various approaches (also referred to as 'micro-optimization'
.