javascript - 不知道是不是变量提升的问题
仅有的幸福
仅有的幸福 2017-06-12 09:29:36
[JavaScript讨论组]
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路线

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号