代码如下:jsvardiv=$('#appendHere');$('#clickMe').on('click',function(){varthat=this;div.append(checkForWindow(this));setTimeout(function(){div.append(checkForWindow(this));div.append('thatisthe'+that.tagName+'
');},300);});functioncheckForWindow(elm){if(elminstanceofWindow){return'thisistheWindow
';}elseif(elm.tagName){return('thisisthe'+elm.tagName+'
');}else{return('thisis'+elm+'
');}}输出结果:(另见:http://jsfiddle.net/dposin/okjr81ev/light/)thisistheBUTTONthisistheWindowthatistheBUTTON问题来了,setTimeout中的checkForWindow(this)为什么没有形成闭包,而that又形成闭包了呢?这样写就能形成闭包?本来我以为是要这样写的:jsfor(vari=0;i<10;i++){setTimeout((function(i){console.log(i);})(i),0);}这两种写法有区别吗?注:我又理解了一下,发现两种都是闭包,只不过所处的上下文环境不一样。但是checkForWindow(this)中的this不是取闭包中的this,而是取了window呢?也是闭包啊,闭包中上下文也有this啊,为什么就要取你setTimeout中的上下文this呢?=======================================好文链接:setTimeout:https://developer.mozilla.org/zh-CN/docs/Web/API/Window/setTimeout闭包:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Closureshttp://www.zhihu.com/question/20019257
www说
开满天机
相关分类