Àí½âjavascript closures ±Õ°ü(¶ÁÊé±Ê¼Ç)
ʲôÊDZհü(closures):
±Õ°ü¾ÍÊÇÄÚ²¿º¯Êýͨ¹ýijÖÖ·½Ê½Ê¹Æä¿É¼û·¶Î§³¬³öÁËÆ䶨ÒåµÄ·¶Î§,Õâ¾Í²úÉúÁËÒ»¸öÔÚÆ䶨Ò巶ΧÄڵıհü.
ÕâÊÇÎÒÀí½âºóµÄÒ»¸ö¶¨Òå,ºÇºÇ!ºÜ»Þɬ°É!²»¹ýû¹Øϵ,¿ÉÒÔÏÈ¿´¿´ÏÂÃæµÄ½²½â.
Ò» ÄÚ²¿º¯Êý(inner function)
javascriptÊÇÖ§³ÖÄÚ²¿º¯ÊýÉêÃ÷(inner function declaration)µÄ±à³ÌÓïÑÔ,
ÄÚ²¿º¯Êý¾ÍÊÇÔÚÁíÒ»¸öº¯ÊýµÄÄÚ²¿¶¨Òå,Èç
function outerFun(){
function innerFun(){
alert('hello');
}
}
º¯ÊýinnerFun¾ÍÊÇÄÚ²¿º¯Êý, ËüÔÚº¯ÊýouterFun·¶Î§ÄÚÊǿɼûµÄ,
Ò²¾ÍÊÇ˵innerFunº¯ÊýµÄÃüÃû¿Õ¼ä(namespace)ÊÇÔÚouterFun·¶Î§Ö®ÄÚ.
ÕýÈ·µ÷ÓÃ:
function outerFun(){
function innerFun(){
alert('hello');
}
innerFun();
}
outerFun(); //alerts "hello"
´íÎóµ÷ÓÃ(error):
function outerFun(){
function innerFun(){
alert('hello');
}
}
innerFun();
ÄÇôÈç¹ûÎÒÏëÔÚº¯ÊýouterFunÍâÃæµ÷Óú¯ÊýinnerFun,ÎÒ¸ÃÈçºÎ×öÄØ?
×ö·¨1:
var globVar;
function outerFun() {
function innerFun() {
alert('hello');
}
globVar = innerFun;
}
outerFun();
globVar();
×ö·¨2:
function outerFun() {
function innerFun() {
alert('hello');
}
return innerFun ;
}
var globVar = outerFun();
globVar();
×ö·¨3:
function outerFun() {
function innerFun() {
alert('hello');
}
return {'innerFun':innerFun} ;
}
var globVar = outerFun();
globVar.innerFun();
ÒÔÉÏÈýÖÖ×ö·¨°ÑÄÚ²¿º¯ÊýµÄ¿É¼û·¶Î§À©´óÁË, ÆäÖÐ×îºóÒ»ÖÖ×ö·¨ÊÇ°ÑÄÚ²¿º¯Êýµ±×öÄäÃû¶ÔÏó{'innerFun':innerFun}µÄÊôÐÔ,²¢ËæÖ®Ò»Æð·µ»Ø.
´ÓÖп´µ½ÔÚjavascriptÀïÃæ,º¯ÊýÃû³Æ¿ÉÒÔµ±×÷ÊÇÒ»ÖÖÒýÓñäÁ¿,ÀàËÆÓÚcÀïÃæÖ¸ÕëµÄ¸ÅÄî,ÔÚÕâÀï,Ëæ×ųÌÐòµÄÖ´ÐÐ
»á²úÉúÁ½¸öÒýÓñäÁ¿Ö¸ÏòÄÚ²¿º¯ÊýinnerFun,Ò»¸öÊÇglobVar(µÚÈýÖÖ×ö·¨ÊÇglobVar.innerFun),ÁíÒ»¸öÊÇÆ亯Êý×ÔÉíinnerFun,
Ö»²»¹ýÕâÁ½¸ö±äÁ¿µÄ¿É¼û·¶Î§²»Ò»Ñù,¼´ÃüÃû¿Õ¼ä²»Ò»Ñù.
javascriptÀ¬»ø»ØÊÕÆ÷»áÔÚº¯Êý×îºóÒ»¸öÒýÓñäÁ¿±»·ÏÆúºó,ÊÍ·ÅÆäËùÕ¼ÓõÄÄÚ´æ.
¶þ ±äÁ¿·¶Î§
Àý1 ÄÚ²¿º¯Êý±äÁ¿
ÔÚÄÚ
Ïà¹ØÎĵµ£º
event´ú±íʼþµÄ״̬£¬ÀýÈç´¥·¢event¶ÔÏóµÄÔªËØ¡¢Êó±êµÄλÖü°×´Ì¬¡¢°´ÏµļüµÈµÈ¡£
event¶ÔÏóÖ»ÔÚʼþ·¢ÉúµÄ¹ý³ÌÖвÅÓÐЧ¡£
eventµÄijЩÊôÐÔÖ»¶ÔÌض¨µÄʼþÓÐÒâÒå¡£±ÈÈ磬fromElement ºÍ toElement ÊôÐÔÖ»¶Ô onmouseover ºÍ onmouseout ʼþÓÐÒâÒå¡£
Àý×Ó
ÏÂÃæµÄÀý×Ó¼ì²éÊó±êÊÇ·ñÔÚÁ´½ÓÉϵ¥»÷£¬²¢ÇÒ£¬Èç¹ûshift¼ü±»°´Ï ......
1¡¢Ö±½ÓÔÚǰ̨µ÷Óà javascript º¯Êý
ºÜ¼òµ¥,ÔÚ head ÔªËØÖ®¼ä¼ÓÈë script ÔªËØ,½« type ÔªËØÉèÖÃΪ " text/javascript "
Èç:
<head runat="server">
<script type="text/javascript" >
function ShowName(str)
{
alert("ÄúµÄÃû×ÖΪ:("+str+")");
}
</script>
<title> ......
Õ⼸Ì죬ÒòΪһ¸öÏîÄ¿ÖеÄbug¶øÍ·Í´¡£
ÕâÊÇÒ»¸öÌõÂëɨÃè³ÌÐò£¬ÎªÁ˱£Ö¤É¨Ã蹤×÷µÄÁ¬ÐøÐÔ£¬ÔÚÒ³ÃæÖÐÀûÓÃ
Javascript×Ô¶¯²¶»ñkeydownʼþ£¬ÒòΪÌõÂëɨÃèǹÔÚÍê³ÉÒ»´ÎɨÃèÈÎÎñºó»á´¥·¢»Ø³µ¼ü£¬ËùÒÔ£¬ÔÚkeydownʼþÖÐÅжÏÊÇ·ñ
keyCode==13£¬È»ºó´¥·¢Ò³ÃæÖÐÒ»¸öÒþ²ØµÄ°´Å¥£¬Ìá½»´ËÊý¾Ý±£´æÖÁ·þÎñÆ÷¡£
³ÌÐòÖУ¬ÎªÌõÂëÊäÈëÎÄ ......
±¾²©¿ÍתÔØÓÚ£ºhttp://www.cnblogs.com/yage/archive/2009/11/20/1607220.html
¶ÔÓÚÕýÔÚ´ÓÊ»òÕß´òËã´Óʱà³ÌµÄÈËÀ´Ëµ£¬ÃæÏò¶ÔÏóÊÇÒ»¸ö¶úÊìÄÜÏêµÄ´Ê£¬¼¸ºõÿһ¸öÈ˶¼ÄÜÁоٳöһЩÃæÏò¶ÔÏóµÄ±à³ÌÓïÑÔ£¬ÀýÈç
C++£¬
JAVA£¬
C#µÈµÈ¡£Æäʵ£¬ÃæÏò¶ÔÏóµÄ˼ÏëÊǶÀÁ¢ÓÚ±à³ÌÓïÑԵģ¬ÀýÈçÔÚ
C#ÖУ¬ÔÚÒ»¸ö¾²Ì¬ÀàµÄ¾² ......