Javascript performance with closure

后端 未结 2 1190
广开言路
广开言路 2021-02-01 23:02
var name = function(n) {
    var digits = [\'one\',\'two\',\'three\',\'four\'];
    return digits[n];
}

var namenew = (function() {
    digits = [\'one\',\'two\',\'thre         


        
2条回答
  •  渐次进展
    2021-02-01 23:25

    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 Contexts and Object. There are three basic types of Context in ECMAscript: Global context, Function contexts and eval contexts.

    Every time you call a function, your engine will spawn it in it's own function context. Also, there is a such called Activation object created. This mystic object is part of a function context which consists out of at least:

    • [[Scope chain]]
    • Activation object
    • "this" context value

    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, the Activation objects from 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 digits variable is stored in the Activation object for namenew. The second when the inner anonymous function is created, it adds that Activation object into its [[Scope]] propertys. When you call digits[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/

提交回复
热议问题