settimeout 作用域问题

本文通过三段JavaScript代码示例,深入剖析了变量作用域、setTimeout行为及this关键字的指向问题,帮助读者理解JavaScript中变量提升、作用域链及异步编程的特点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

无意中看到以下代码:


第一段代码:

	var a = 6;
	setTimeout(function () {
		alert(a);
		a = 666;
	}, 1000);
	a = 66;

输出为66



第二段代码:

	var a = 6;
	setTimeout(function () {
		alert(a);
		var a = 666;
	}, 1000);
	a = 66;

输出为undefined




第三段代码:

var show = function(){
            alert(this+" is all");
}
var Obj = function(){
            this.show = function(){
                alert(this+" is obj");
            }
            this.time = function(){
                var self = this;
                //setTimeout(function(){this.show();}, 2000);//window is all
                //setTimeout(function(){self.show();}, 2000);//Obj is obj
                //setTimeout("this.show()", 2000);//window is all
                //setTimeout("self.show()", 2000);//window is all
                //setTimeout(this.show, 2000);//window is obj
                //setTimeout(self.show, 2000);//window is obj
            }
}
        var obj = new Obj();
        obj.time();

setTimeout() 和 setInterval() 调用的代码或者函数是全局作用域的






看两段代码就能分析1和2的区别:

var scope="global";
function t(){
    console.log(scope);
    scope="local"
    console.log(scope);
}
t();

输出:

global

local


var scope="global";
function t(){
    console.log(scope);
    var scope="local"
    console.log(scope);
}
t();

输出:

undefined

local


这里为什么会输出undefined,因为上面代码相当于:

var scope="global";
function t(){
    var scope;
    console.log(scope);
    scope="local"
    console.log(scope);
}
t();

这个要看我下一篇转发的文章。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值