简体   繁体   中英

Is 'global' a function in Javascript?

I am studying hard what the closure is in Javascript. According to MDN, closures are created every time a function is created, at function creation time. However, many articles and answers in Stack Overflow says that the concept of closure needs the relationship between inner function and outer function and their variables. So, I wonder whether 'global' is the kind of a function which executes at runtime of global scope(or global execution context) or not. If 'global' is a function, all of the functions in script are maybe inner functions, I guess. Please answer me if you are fully understanding closures, and execution contexts. Thank you!

your question is a very genuine one:). What I get from your question is that your confusion is in 'global' in JavaScript. It is not clear from your question if you need help in closures and execution context, so to keep the answer short I'll focus on "global" only.

So global in JavaScript is the global execution context. It is more like complier running the code. If you have experience in any programming language say Java. You may relate to this. The place where you write functions is not a function itself. So we can safely say global is not a function rather an execution context.

Same way, the functions defined inside a global execution context are not inner functions. They are simply functions.

Maybe you are confused in this, because you feel the variables declared globally can be accessed inside the function declared in global concept, this is simply because of scope of a variable and has nothing to do with closures.

When we execute our code, one of the very first things that the JavaScript engine does is to create a global execution context. This has the same purpose as function execution context, but at the global level with some more particularities. Now, once GEC got created - JS engine moves line by line and starts to execute other functions with their own function execution context!

So as per your question, global is just an execution context that gets created only once at the beginning with some extra features.

Hope this could clear your doubt.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM