Home >Web Front-end >JS Tutorial >JavaScript variable scope analysis (code example)

JavaScript variable scope analysis (code example)

青灯夜游
青灯夜游forward
2018-10-23 17:32:591995browse

What this article brings to you is JavaScript variable scope analysis (code example). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Variables are divided into two types: local variables and global variables

Let’s look at the following example:

var myVariable = 'global';
myOtherVariable = 'global';

function myFunction(){    
    var myVariable = 'local';    
    return myVariable;
}

function myOtherFunction(){    
    myOtherVariable = 'local';    
    return myOtherVariable;
}


console.log(myVariable); //{行1}    global
console.log(myFunction()); //{行2}   local

console.log(myOtherVariable); //{行3}   global
console.log(myOtherFunction()); //{行4}   local
console.log(myOtherVariable); //{行5}  local

Line 1 outputs global because it is a global variable;

Line 2 outputs local, because myVariable is a local variable declared in the myFunction function, so the scope is only in myFunction;

Line 3 outputs global, because we initialized the global variable myOtherVariable in the second line ;

Line 4 outputs local. In the myOtherFunction function, there is no modification of the keyword var, so the global variable myOtherVariable is referenced here and copied loacl;

Local is output in line 1. This is because in The value of myOtherVariable has been modified in line 4;

The above is the detailed content of JavaScript variable scope analysis (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete