Some experts may already know about these two things, but I think these two things still have some value. So I 'd like to share them with you here.
. The following code is available:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function test (){
With (location ){
Var temp = "an url ";
}
Alert (temp );
}
Test ();
</Script>
What will be output when this function is called? It may be thought that it will pop up undefined, but in fact, it pops up the "an url" string, which involves a concept of variable scope in JavaScript.
In JS, each scope has a corresponding "variable object" (this is not necessarily accurate, just know that there is such a thing ), the identifier of the current scope definition is stored here. At the beginning of the JS program, it will enter the global scope. In our program, because the test function is defined in the global scope, so the "variable object" Here stores the identifier of the test function. Next, we call the test function and enter the scope of the test function. The scope of the test function also has its own "variable object". When we enter the scope of the test function, the identifier stored in the global scope is also copied. Therefore, the identifier defined in the global scope can be accessed in the test function, but in the outer scope, cannot see the content of the inner layer. In this case, the alert (temp) here will output undefined, because temp is defined in the internal scope. But why can I find the identifier defined in the inner-layer scope here?
Because the "variable object" defined in the with statement block is read-only, the identifiers defined in the with statement block cannot be stored in the current layer, but stored in the previous scope, that is, the scope of the test function. Therefore, our alert (temp) statement can access the temp variable defined in the internal layer. The same situation occurs in try catch statements.
. Javascript does not have the concept of statement blocks. The Code is as follows:
Copy codeThe Code is as follows:
If (true ){
Var temp = "oh ";
}
Alert (temp );
A few simple lines of code. Based on the common programming language experience, we will think that alert statements will report errors, but this is not the case, the alert statement outputs the "oh" string normally
The concept of statement block does not exist in Javascript.
The two examples above are very simple. Maybe they are not very high-tech and many experts should have already understood them. However, these two language features should be useful. Maybe after learning about these features, when writing JS, there will be fewer errors, so I 'd like to share it with you, hoping to help you write JavaScript.