javaScript 载入自执行
1.注册可以直接调用f()中的b(),c(),d() .原因?自己想。
<!DOCTYPE html> <html> <head> <meta charset=gb2312 /> <title>js</title> <script> function f(){ var a = 1; b = function(){ alert(a); } c = function(){ a++; } d = function(x){ a = 100; } } </script> </head> <body> <input type="button" value="f" onclick="f()"/> //需要先点击这个,才能点击其他,否则出错 <input type="button" value="alert a" onclick="b()"/> <input type="button" value="a++" onclick="c()"/> <input type="button" value="a=100" onclick="d()"/> </body> </html>
2.f()改为匿名函数----载入自执行
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset=gb2312 /> 5 <title>js</title> 6 <script> 7 (function(){ 8 var a = 1; 9 b = function(){ 10 alert(a); 11 } 12 c = function(){ 13 a++; 14 } 15 d = function(x){ 16 a = 100; 17 } 18 })(); 19 </script> 20 </head> 21 22 <body> 23 <div>f()改为匿名函数,载入后自执行</div> 24 <input type="button" value="alert a" onclick="b()"/> 25 26 <input type="button" value="a++" onclick="c()"/> 27 <input type="button" value="a=100" onclick="d()"/> 28 29 </body> 30 </html>