settimeout 作用域问题

来源:互联网 发布:php程序源码 编辑:程序博客网 时间:2024/05/21 15:40

无意中看到以下代码:


第一段代码:

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

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




0 0
原创粉丝点击