Interesting about Javascript

Source: Internet
Author: User

JavaScript is an interesting language. It is not only interesting but also naughty. Browsers with different kernels may have different performance during parsing, we will discuss some JavaScript expressions that are common in actual development but may not be too concerned about at the same time. Here are several conventions:
Because JavaScript is an explanatory language, there is no compilation process, but there will be a syntax check and execution environment building before the script is executed. Let's call this process preprocessing.

When using the var keyword to declare a variable or function, we call this process a variable declaration and a function declaration. When using an expression like function fn () the way to define a function is called function definition.

The test environment of the instance in this article is the IE 9, FF4.0, and chrome 14.0 browsers installed on my computer with different kernels.

Okay, next let's get started. Let's mainly look at some simple demos to observe and understand how the browser initializes JavaScript variables and functions. The main points involved include the scope of JavaScript and the execution environment, for friends who are not familiar with this convenience, refer to the link at the end of the article and read some simple demos.


1. function declaration:

Fn (); // output 2var fn = function () {console. log (1);} function fn () {console. log (2);} fn (); // output 1

The method defined by the function is accessed when fn is called for the first time, and the method defined by the function is accessed by the second call. Who overwrites the entire process from preprocessing to execution, who has a higher priority?


2. Access to local variables and global variables:

Var num1 = 1; function fn (num3) {console. log (num1); // output undefined console. log (num3); // output 4 console. log (num4); // throw the error "num4 is not defined" console. log (num2); // throw the error "num2 is not defined" var num1 = num4 = 2; num2 = 3; var num3 = 5;} fn (4 );
The fn method outputs four variables in sequence. I don't know whether the result is different from what you expected. The first output parameter num1 is declared in both the local and global environments, it is understandable that the priority of local variables is higher than that of global variables. What is different here is that num1 is accessed before the variables are declared. This indicates that a storage space has been allocated for the local variables when the execution environment is constructed in the preprocessing phase, the initial value is undefined. The second output variable num3 is included in both arguments and local variables. The output variable is the parameter variable in arguments. If the previous conclusion is true, the variables in arguments overwrite the variables in the local environment. That is to say, the priority of variables defined by variables is higher than those defined in the arguments object array. When the third output is num4, an error is reported, indicating that variables other than the first variable in the continuous value assignment operation are treated as global variables, and there is no relevant definition in the global environment, the fourth num2 output error is also considered a global variable. The errors in these two locations can be referenced in the following sentence: "A personal self-scan will not allow others to get Frost ", that is to say, in the preprocessing phase, an independent execution environment only maintains its internal variables and ignores the variables in other environments.

3. function call:

function   fn(t){    t();    function t(){        console.log(2);    }    var t = function(){        console.log(3);    }}fn(function(){console.log(1)});  //output  2

The main purpose of this demo is to compare the priority of three methods: arguments, function definition, and function declaration. From the result, we know that the output is a function defined by function declaration, the conclusion from the previous example is that the variables in arguments will overwrite the variables defined by the var method. Here, the variables in arguments are overwritten by the function-defined method, so we can get the following conclusion: the method for declaring a function as a variable (var t = function () {}) has the highest priority. It is initialized during the preprocessing phase and overwritten by the variable in arguments before execution, finally, it is overwritten by the variables created through function t () {}). After this process is completed, the program starts to run.

As we all know, JavaScript does not have block-level scopes, and browsers are also consistent. For example, the following code:

if(true){var m= 1;}console.log(m); //ouput 1

4. test:

console.log(fn.toString());if (true) {   function fn(){ return 1; }}else {   if(false){      function fn(){ return 2; }   }}

If you do not prevent yourself from testing, "function fn () {return 2 ;}" will be output in IE and chrome, and an error will be reported in FF. If the code is changed:

if (true) {     function fn(){ return 1; }  }else {     if(false){       function fn(){ return 2; }     }}console.log(fn.toString());

The output result does not change in IE and chrome. In FF, it becomes "function fn () {return 1 ;}". This result may not be the same as you expected, I have read some websites on the Internet and I have different opinions about this. Some of them are FF bugs. I personally think it should not be a bug. After all, every browser vendor may have differences when implementing ECMAScript, you cannot regard yourself as a mistake because it is different from what most people do. Why is there such a difference? I personally think there are some differences in block scope processing when building the execution environment in the pre-processing stage. First, Let's confirm one thing, if a variable is declared through the var keyword in block-level scope, no matter whether the variable is accessed before or after the statement is declared, when building the execution environment, the system will find all the variables defined by var in the current domain and allocate space. However, the function definition method is different, IE and chrome will initialize the function object during construction, and the subsequent definition will overwrite the previous definition. From the code above, we can also see that the function definition has been processed in the preprocessing phase, in the code execution phase, the definition of a function is directly ignored regardless of the Code logic (this is important), and function definitions in block-level scopes are ignored during preprocessing in FF, initialization is performed again during code execution. The two implementation methods are more reasonable in terms of performance and efficiency. Therefore, we cannot classify this implementation method as a bug, of course, this is purely a personal opinion.


5. About the name function expression:

fn = function() {return true;};gn = function() {return false;};(function() {   fn = function fn() {return false;};})();console(fn());

True output in IE8 and earlier versions, false output in IE9, FF, and chrome. Well, let's first discuss the naming function expressions in the following format:

var fn = function fn_alias(){   console.log(fn_alias.toString());};

When declaring a function, specify an alias for it. This alias can be accessed externally in IE8 or later versions, and can only be accessed within the function in IE9, FF, or chrome versions, this is why DEMO5 is like that. External access may cause many problems, such as variable name pollution. Therefore, we recommend that you do not use this method in actual development.

Okay. If you have talked so much about it, you can smile. Finally, in a simple summary, it is necessary to understand the process of parsing JavaScript in the browser when developing the front-end, so as to reduce unnecessary errors, we will continue to discuss these interesting questions later.


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.