javascript - 不知道是不是變數提升的問題
仅有的幸福
仅有的幸福 2017-06-12 09:29:36
0
1
550
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)
phpcn_u1582

既然你有疑問,把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路線

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板