一:作用域和闭包
/* 受bar函数声明的位置所影响,foo()的局部作用域在执行完后没有被回收(内存的释放); 原因是bar函数本身还在使用,bar()依然持有对该作用域的引用,而这个引用就叫作闭包。即bar()对foo()该作用域的引用. */ //代码一: /* function foo() { var a = 2; function bar() { //此时bar还没有进行定义,在外部调用的时候他是不存在的. console.log('foo函数的局部变量:',a); } return bar; //返回该函数的地址 } var s = foo(); console.log(s); console.log('执行函数bar'); console.log(' '); s(); */ //代码2: /* var fn; //全局变量 function test() { var a = 2; function bar() { console.log('执行函数bar()') } baz(bar); return bar; } function baz(s) { console.log('在函数baz中调用bar()函数'); s(); } fn = test(); */ //setTimeout()为window对象的内置方法,对于window对象来说在使用其方法时可以不使用点运算符. function wait(message) { setTimeout(function timer() { //setTimeout():设置在指定的毫秒数后执行的函数或计算表达式。 console.log(message); },10000) } wait('hello,cloure!'); function setupBot(name,selector) { $(selector).click(function activator() { console.log('Activating:'+name); }); } setupBot('Closure Bot 1','#bot 1'); setupBot('Closure Bot 2','bot 2');
二:通过:匿名函数的定义,和返回函数的函数.来理解作用域。
1:注意函数名:
<!DOCTYPE html> <html> <head> <title>函数</title> </head> <script type="text/javascript"> var c = function() /*用c来引用匿名函数*/ { document.write("执行匿名函数"); var s = test(); /*s是局部作用域*/ s(100,50);/*执行的是函数test_son*/ console.log(typeof(test_son)); //undefined,为什么是undefined,因为他已经被s引用了。 console.log(typeof(s));//function return 0; } function test()/*返回函数的函数*/ { var b = 23; /*局部作用域test中的变量*/ function test_son(x,y)/*注意不要这样使用functiontest_son(var x,var y)在函数的参数中这样定义变量说明x,y是这个块的作用域中的变量.*/ { console.log("形参x,y="+x+","+y); console.log("b"); } return test_son;/*返回的是函数的地址*/ } c(); </script> <body> </body> </html>
2:方法被封装到了立即执行匿名函数中,如果不添加返回值,外部是访问不到的,添加返回值后,在全局可以通过“匿名函数.函数名()”的方式进行调用。并且可以隐藏一些私有属性和元素,私有空间的函数和变量也不会影响全局作用域,可见这种方式是最理想的方式。大部分第三方库都使用这种形式,例如jQuery。
<!DOCTYPE html> <html> <head> <title>作用域</title> </head> <script type="text/javascript"> var bigfun = (function()/**/ { var big = 12; function add(x,y) { var a = 12;/*改变量的作用域:*/ console.log("bigfun函数中的变量"+big); return x+y;/*有返回值的*/ } function sum() { document.write("sum是没有返回值的函数"); return 0; } function divide(a) { document.write(a); document.write("执行divide函数,来输出var big"+big); return 0; } return{ /*返回*/ add:add, //左边的为bigfun对象的属性,右边为函数地址。这里是用属性引用函数的方式。 sum:sum, divide:divide } })(); var x = bigfun.add(100,100);//输出:bigfun函数中的变量12 console.log(x);//输出:200 console.log(typeof(bigfun));//输出:object //bigfun是什么数据类型.? //数组的定义? </script> <body> </body> </html>