var name = function(n) {
var digits = ['one','two','three','four'];
return digits[n];
}
var namenew = (function() {
digits = ['one','two','three','four'];
return function(n) {
return digits[n];
}
}());
Both the versions result in the same output, however it is said that the second version is much faster than the first version.
As I understand, first version executes the function everytime where as the second version stores the result of execution. That is what confuses me as a functional/regular OOPS programmer.
How can one save a function with its inner context? What is happening under the hood? Can some one pls clarify?
The real answer to that question would be about 3 pages long. But I try to make it as short as possible. ECMA-/Javascript is all about
Execution ContextsandObject. There are three basic types of Context in ECMAscript:Global context,Function contextsandeval contexts.Every time you call a function, your engine will spawn it in it’s own
function context. Also, there is a such calledActivation objectcreated. This mystic object is part of afunction contextwhich consists out of at least:There may be more properties on different engines, but these three are required for any implementation of ES. However, back to the topic. If a function context is invoked, all
parent contexts(or more precisly, theActivation objectsfrom the parent contexts) are copied over into the[[Scope]]property. You can think of this property like an array, which holds (Activation-) Objects. Now, any function related information is stored in the Activation object (formal parameters, variables, function declarations).In your example, the
digitsvariable is stored in the Activation object fornamenew. The second when the inner anonymous function is created, it adds thatActivation objectinto its[[Scope]]propertys. When you calldigits[n]there, Javascript first tries to find that variable in its own Activation object. If that fails, the search goes into the Scopechain. And voila, there we found the variable because we copied the AO from the outer function.I already wrote too much for a short answer, but to really give a good answer to such a question you have to explain some basic knowledge about ES here. I guess that is just enough to give you an idea what really happens “under the hood” (there is a lot more to know, if you want to read more I’ll give you some references).
You asked for it, you get it:
http://dmitrysoshnikov.com/ecmascript/javascript-the-core/