search

Home  >  Q&A  >  body text

javascript - I don’t know if it’s a problem with variable promotion

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. 

The result is that the direct output box1 is null.

cleared Interval as box1 is null now
false

Is it because var will declare local variables first? As a result, box = null directly after declaration. Then the content in else is output?

仅有的幸福仅有的幸福2729 days ago514

reply all(1)I'll reply

  • phpcn_u1582

    phpcn_u15822017-06-12 09:31:36

    Since you have questions, wouldn’t you know the result after removing var?
    It is indeed a variable promotion, you might as well output what box1 is in the timer

    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);

    The result is that undefined is output first, not null as you think.
    is actually equivalent to

    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)

    So, the timer was triggered just after reaching the point, and found that box1 was declared, but the actual assignment had not yet started, so the if took the else route

    reply
    0
  • Cancelreply