js作用域

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值