var str = "globel";
function t1() {
console.log(str);//打印globel
console.log(str2);//打印 str2 is undefined错误
str2 = "local";
}
t1();
打印str2时还没有执行到str2=”local“这一步,首先查找t1()里面没有,又查找window里面没有。
二、
var str1 = "globel";
function t1() {
console.log(str1);//打印globel
console.log(str2);//打印 undefined
var str2 = "local";//多加了一个var声明
}
t1();
js代码的执行自上而下,但是js代码在整体运行分:词法分析期和运行期。
以上面结果为例
先分析t1()函数——>t1{var str2//分析出t1内有str2局部变量,注意此时函数未执行,因此str2时undefined}
执行t1()函数,——>console.log(str1);//globel,console.log(str2)//undefined,str2="local"此时str2的值为local
三、
var str = "globel";
function t1() {
console.log(str);//打印globel
console.log(window.str2);//打印undefined
str2 = "local";
}
t1();
console.log(str2);//打印local