不知道是不是变量提升的问题

function Box(age) {
    this.name = 'ss';
    this.age = age;
    this.flag = true;
    return this;
} //定义一个构造函数

var box1 = new Box(10); // new出一个实例

setTimeout(function () {
    box1.flag = false;
    console.log(box1.flag);
}, 5000); //五秒钟之后把 实例box1里面的flag变为false.


var inter = setInterval(function () {
    if (box1) {
        console.log(box1);
        if (!box1.flag) {
            box1 = null;
            var box1 = new Box(20);
        }
    } else {
        console.log('cleared Interval as box1 is null now');
        clearInterval(inter);
    }

}, 1000); //每一秒种先控制台打印出box1, 如果flag为false, 那么就销毁box1,然后再new出一个box1. 

结果是直接输出box1是null.

cleared Interval as box1 is null now
false

请问是不是由于var会优先声明局部变量. 导致声明后直接box = null. 然后就输出 else里面的内容?

阅读 1.6k
1 个回答

既然你有疑问,把var去掉才看看结果不就知道了?
确实是变量提升,不妨在定时器里先输出box1是啥

var inter = setInterval(function () {
    console.log(box1);    
    if (box1) {
        console.log(box1);
        if (!box1.flag) {
            box1 = null;
            var box1 = new Box(20);
        }
    } else {
        console.log('cleared Interval as box1 is null now');
        clearInterval(inter);
    }
 },1000);

结果是先输出undefined不是你认为的null。
实际上相当于

var inter = setInterval(function () {
  var box1;
   if (box1) {
        console.log(box1);
        if (!box1.flag) {
            box1 = null;
            box1 = new Box(20);
        }
    } else {
        console.log('cleared Interval as box1 is null now');
        clearInterval(inter);
    }
},1000)

于是呢,定时器刚到点触发,发现声明了box1,但实际赋值还没开始,所以if走else路线

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题