var scope="global"; function t(){ console.log(scope); //"global" scope="local" console.log(scope); //"local" } t(); console.log(scope); //"local"
var scope="global"; function t(){ console.log(scope); //"undefined" var scope="local" console.log(scope); //"local" } t(); console.log(scope); //"global"
在变量解析过程中首先查找局部的作用域,然后查找上层作用域。在第一段代码的函数当中没有定义变量scope,于是查找上层作用域(全局作用域),进而进行输出其值。但是在第二段代码的函数内定义了变量scope(无论是在console之后还是之前定义变量,都认为在此作用域拥有变量scope),于是不再向上层的作用域进行查找,直接输出scope。但是不幸的是此时的局部变量i并没有赋值,所以输出的是undefined。
//所以根据函数作用域的意思,可以将上述第二段代码重写如下: var scope="global"; function t(){ var scope; console.log(scope); scope="local" console.log(scope); } t();由于函数作用域的特性,局部变量在整个函数体始终是由定义的,我们可以将变量声明”提前“到函数体顶部。
var b; //第1步 function fun(){ b = "change"; } alert(b);//输出undefined,由于第1步只定义未赋值 var b; //第1步 function fun(){ b = "change"; } fun(); //调用上述函数 alert(b); //输出change当使用var声明一个变量时,创建的这个属性是不可配置的,也就是说无法通过delete运算符删除。
<html> <head> <script type="text/javascript"> function buttonInit(){ for(var i=1;i<4;i++){ var b=document.getElementById("button"+i); b.addEventListener("click",function(){ alert("Button"+i);},false); } } window.onload=buttonInit; </script> </head> <body> <button id="button1">Button1</button> <button id="button2">Button2</button> <button id="button3">Button3</button> </body> </html>当注册事件结束后,i的值为4,当点击按钮时,事件函数即function(){ alert("Button"+i);}这个匿名函数中没有i,根据作用域链,所以到buttonInit函数中找,此时i的值为4,所以弹出”button4“。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>闭包</title> </head> <body> <ul id="list"> <li>第1条记录</li> <li>第2条记录</li> <li>第3条记录</li> <li>第4条记录</li> <li>第5条记录</li> <li>第6条记录</li> </ul> <script type="text/javascript"> function tt(nob) { this.clickFunc = function() { alert("这是第" + (nob + 1) + "记录"); } } var list_obj = document.getElementById("list").getElementsByTagName("li"); //获取list下面的所有li的对象数组 for (var i = 0; i<= list_obj.length; i++){ console.log(list_obj[i]) list_obj[i].onmousemove = function(){ this.style.backgroundColor = "#cdcdcd"; } list_obj[i].onmouseout = function() { this.style.backgroundColor = "#FFFFFF"; } //list_obj[i].onclick = function() { // alert("这是第" + i + "记录"); //不能正常获取 alert出来的都是:“这是第6记录” //} var col = new tt(i); //调用tt函数 list_obj[i].onclick = col.clickFunc; //执行clickFunc函数 } </script> </body> </html>