Home > Web Front-end > JS Tutorial > body text

javascript variable scope code analysis_javascript skills

WBOY
Release: 2016-05-16 18:51:01
Original
1095 people have browsed it

Code Listing 1-1 Example showing the variable scope of JavaScript
//Set the global variable foo and set it to "test"
var foo = "test";
//In the if block
if(true){
//Set foo to 'new test'
var foo = "new test";
}
//As we can see, now foo is equal to 'new test' '
alert(foo == "new test");
//Create a new function that will modify variable foo
function test(){
var foo = "old test";
}
//However, when called, foo only works within the function scope
test();
//This confirms that foo is still equal to 'new test'
alert(foo = = "new test");
An interesting feature of browser-based JavaScript is that all variables belonging to the global variable scope are actually properties of the window object.
Code List 1-2 Global scope and window object in javascript
//A variable under the global scope stores the string 'test'
var test = 'test';
/ /You can see that our global variable is 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 used within the scope of this function.
Code Listing 1-3 Implicit global scope variable declaration
//A function that sets the value of foo
function test(){
foo = "test";
}
//Call this function to set the value of foo
test();
//We find that foo is now in the global scope
alert(window.foo == "test");

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template