JavaScript Virtual Entry Function Main method

Source: Internet
Author: User

This article we virtual a JavaScript entry main function as the starting point of the program, so that we can have more in-depth learning and understanding of JS.

one, the actual entry of JavaScript file

JavaScript files to the JS engine runtime, the JS engine is from the top of the JavaScript file from up to down the execution of the statement, until the end of the file to execute every JS code.

II. scope chain, global scope and global object of JavaScript

Each function in JavaScript produces a new scope when it executes. Specifically, a new scope is created when the process enters the function, and the scope is destroyed when the function execution completes exiting. The parameters of a function, local variables are bound to this scope, and when the function call completes the scope destroy, they are destroyed. Of course, in special cases, if some variables in the scope are still referenced when the function returns, the scope and the referenced variables will not be destroyed to form the so-called closure.

On the other hand, we know that functions can be nested, so scopes can also be nested. When the function is defined, the JS engine sets a built-in property called [[scope]] to each function, which points to the lexical scope of the external function. In this way, multiple scopes form a chain structure called a scope chain. In general, there is only one scope chain at any time, that is, starting from the scope of the function being executed, the layers are traced back to the outermost global scope.

[Note]: The function on the scope chain is JS source layer nested functions, with the function of the execution of the order or function call stack, which is also the lexical scope of the origin of this name.

A global scope is a special scope that is not a function scope, but it is the outer scope of all function scopes and the end point of all scope chains. So as long as the program does not exit, the global scope always exists, and the variables within the global scope are also valid.

[function 3 scope]-->[function 2 scope]-->[function 3 scope]-->[global scope]

In addition, there is a global object that corresponds to the global scope. In the browser, the global object is the Window object. The global object is a special object:

Variables defined in the global scope are bound to the global object.
Variables defined in any scope, if defined without using the var keyword, are bound to the global object.
In the global scope, this points to the global object.

The features listed above show that if the global scope is treated as an object, then it is actually a global object. In addition, this explains why the following four statements are equivalent in the global scope:

var a = 1;
A = 1;
WINDOW.A = 1;
THIS.A = 1;

three, the fictitious main entry function

Since all are scopes, why should there be a special global scope? We always like simplicity, consistency, and try to avoid complications, specificity. So naturally, we wonder if we can make the global scope look different from the scope of the function? The answer is yes. We can do this idea:

We imagine that when the JS engine executes the source file, the code in the file is packaged into a function called Main. This main function is then used as the entrance to the program.

In other words, suppose a JS file has such a code:

var a = 1;
var b = 2;
function add (x, y) {
var z = x + y;
return z;
}
Console.log (Add (A, b));


The JS engine wraps the program into a main function before it starts executing:

The fictitious main function function
main () {
var a = 1;
var b = 2;
function add (x, y) {
var z = x + y;
return z;
}
Console.log (Add (A, b));


Then, call this main function:

main._current_scope_ = window; Set global scope (object) to Window
Main.call (window)//point this to window

Iv. What is the point of doing so?

(1) JS also has the entry function main, consistent with other languages.
(2) The concept of global scope is omitted, or the global scope becomes a function scope.
(3) through the above to the main function of the call process, you can understand the global scope of the origin of those special characteristics.
(4) The last point, all JS source code as a function, is to talk about the event queue, the event loop to do bedding.



A unified portal for JavaScript programs

JavaScript is a scripting language, where the browser is downloaded to execute there, this feature is convenient for us to program, but also easy to make the program fragmented, too dispersed. When we need to use the JS Web page of a very long time, a variety of JS tags scattered to the Web page, the page loaded to where to execute, their own independent operation, although to meet the needs, but to our maintenance bring great trouble, no organizational! To solve this problem, we make the JS code a unified Portal:

JavaScript in a Web page should be functionally divided into two parts:


(1) Part of the framework: the role of this section is to organize the JavaScript code, including the definition of global variables and namespace methods. It has nothing to do with specific applications, and each page needs to contain the same framework.
(2) Application section: Provide the functional logic of the page, different pages will have different functions, so the different page application part of the code is not the same.
Through the following section of code, let us have a deeper understanding of the JS code framework and application parts:


<div>  <!--  This is a section of HTML code  -->  xxxxxxxxxxxxxxxx </div> <script type= "
Text/javascript >  //Define namespace Methods  var GLOBAL={};  global.namespace = function (str) {  for (i= (arr[0]== "GLOBAL")  ? 1 :  0; i<arr.length; i++) {   o[arr[i]] = o[arr[i]] | |
 {};
   o = o[arr[i]];
&NBSP;&NBSP}  }  </script> <script type= "Text/javascript" >  function init () {   //function: A    (function () {   var a = 111; b= "Hello";  
  global.namespace ("A.cat");
   global.namespace ("A.dog");    global.
a.cat.name =  "Xiaomao";    global.
a.dog.name =  "Wangcai";    global. A.cat.eat = function () {        }    global. A.dog.eAt = function () {   }    global.
a.str2 = a;    global.
a.str = b;
&NBSP;&NBSP}) ();   //function: B    (function () {   var a, c= "EFG";    
Global.namespace ("B");    global.
b.str = c;
&NBSP;&NBSP}) ();   //function: C    (function () {   var a=global. A.str2, b=global.
A.STR;
   var d= "This is a demo";
      }) ();   //function: D    (function () {   var test=global.
B.STR;
   alert (test);
&NBSP;&NBSP}) &nbsp} </script> <div>  <!--  This is a section of HTML code  -->  xxxxxxxxxxxxxxxx </div>
In the above code, the method of defining namespaces is the framework part of our JS code, this part of the code is our every page of the JS code to be used. Functions A, B, C, D four Code is our application section, in different pages to achieve different functions.
Perhaps you've found that in the above code, the biggest difference between us and the last one is that we have an init function, which is the entry function we're going to be doing today. In the avoidance of JS conflict, our different functional code segments are scattered across the entire HTML code, and here we will use the functional code unified into the INIT function.
Next, we need to call this entry function (init) at the appropriate time to complete the initialization of the page program. So when is the most appropriate time to call? First of all, we already know that JavaScript is a scripting language, and its biggest feature is where to execute it, and if you program a DOM node and the DOM node is not loaded, the program will complain. As in the following code:
<script type= "Text/javascript" >
alert (document.getElementById ("Demo"). InnerHTML);
</script>
<div id= "Demo" >

In this code, the normal JS code should be pop-up ID for the content of the DOM node, but the reality is, in the execution of the script, the demo node has not loaded, so document.getElementById ("demo") can not find the demo node. To solve similar problems, we must ensure that the nodes required by the JS script load must be loaded.

How can I guarantee that when the JS script executes, the DOM nodes are loaded? The onload event is triggered when all the nodes in the page are loaded, so that we can listen for the OnLoad event of the Window object, and then call the script when the window triggers the OnLoad event to solve our problem. Look at the following code:

<script type= "Text/javascript" >
window.onload = function () {
alert (document.getElementById ("Demo"). InnerHTML);
}
</script>
<div id= "Demo" >

In this way, when the page is loaded into the JS script, the script does not execute immediately, but waits until after window.onload to execute, which ensures that all the required nodes in the script are loaded. As we said earlier, the code for the Application section is best placed in a unified entry function, so the complete code should now be:

<script type= "Text/javascript" >
function init () {
alert (document.getElementById ("Demo"). InnerHTML);
window.onload = init;
</script>
<div id= "Demo" >

Now it seems that our problems have been resolved, but not perfect, because window onload event requires all the elements in the Web page all loaded after the trigger, if the page has a large number of pictures, the load time will be very long, then our initialization function will be extended for a long time will be implemented, This is also a very bad user experience way. So how do we solve this problem?
Domready and Window.onload play a very similar role, but the former only determines whether all the DOM nodes in the page have been generated, and whether the content of the node is loaded, it does not care. All, Domready has a faster trigger speed and is more responsive to our needs. What needs to be noted is that Domready is not a native JavaScript-supported event and cannot be invoked directly like window.load, which we typically need to combine with the JS framework. Let's take jquery for example:

<script type= "Text/javascript" src= "Http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" ></ script>
<script type= "text/javascript" >
function init () {
alert (document.getElementById (" Demo "). InnerHTML);
}
$ (document). Ready (init);
</script>
<div id= "Demo" >

Now we're going to refine our first piece of code and complete the code list as we've just said:

<script type= "Text/javascript"  src= "http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/ Jquery.min.js " ></script> <div>  <!--  This is a section of HTML code  -->   Xxxxxxxxxxxxxxxx </div> <script type= "Text/javascript" >  //define Namespace Method  var global={}
;  global.namespace = function (str) {  for (i= (arr[0]== "GLOBAL")  ? 1 :  0; i<arr.length; i++) {   o[arr[i]] = o[arr[i]] | |
 {};
   o = o[arr[i]];
&NBSP;&NBSP}  }  </script> <script type= "Text/javascript" >  function init () {   //function: A    (function () {   var a = 111; b= "Hello";  
  global.namespace ("A.cat");
   global.namespace ("A.dog");    global.
a.cat.name =  "Xiaomao";    global. a.dog.name =  "Wangcai";    global. A.cat.eat = function () {        }    global. A.dog.eat = function () {   }    global.
a.str2 = a;    global.
a.str = b;
&NBSP;&NBSP}) ();   //function: B    (function () {   var a, c= "EFG";    
Global.namespace ("B");    global.
b.str = c;
&NBSP;&NBSP}) ();   //function: C    (function () {   var a=global. A.str2, b=global.
A.STR;
   var d= "This is a demo";
      }) ();   //function: D    (function () {   var test=global.
B.STR;
   alert (test);
&NBSP;&NBSP}) &nbsp} </script> <div>  <!--  This is a section of HTML code  -->  xxxxxxxxxxxxxxxx </div> <div>  <!--  This is a section of HTML code &NBSP;-->  xxxxxxxxxxxxxxxx </div> ... <script>       $ (document).
Ready (init); </script>

So our JS code tends to be perfect, all global scope functions are placed under the global namespace, effectively control the window scope of the number of functions, reduce the JS conflict hidden trouble. It then provides a unified entry function init for the application of part JS, which is invoked at the end of the Domready.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.