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裡面的內容?
phpcn_u15822017-06-12 09:31:36
既然你有疑問,把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路線