Javascript variable scope code analysis

Source: Internet
Author: User

Code List 1-1: An Example of javascript variable scope
// Set the global variable foo to "test"
Var foo = "test ";
// In the if Block
If (true ){
// Set foo to 'new Test'
Var foo = "new test ";
}
// As we can see, foo is now 'new Test'
Alert (foo = "new test ");
// Create a new function that will modify the variable foo
Function test (){
Var foo = "old test ";
}
// However, when calling, foo only works within the function Scope
Test ();
// Check whether foo is equal to 'new test'
Alert (foo = "new test ");
An interesting feature of browser-based javascript is that all variables in the global variable scope are actually properties of the window object.
Code List 1-2 global scope and window object in javascript
// A global variable that stores the string 'test'
Var test = 'test ';
// You can see that our global variables are consistent with the test attribute of the window object.
Alert (test = window. test)
Finally, if the variable is not explicitly defined, it is globally defined, although it may only be used within the scope of this function.
Code List 1-3 implicit global scope variable Declaration
// A function with the foo value set
Function test (){
Foo = "test ";
}
// Call this function to set the value of foo
Test ();
// We found that foo is under the global scope.
Alert (window. foo = "test ");

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.