第一段代码,输出结果为:NaN
<script type="text/javascript">
var sum=new function(a,b)
{
alert(a+b);
}
sum('a','b');
</script>
第二段代码,输出结果为ab
<script type="text/javascript">
var sum=function(a,b)
{
alert(a+b);
}
sum('a','b');
</script>
这是why啊?
1ï¼è°ç¨å ³é®åfunctionæ¥æé
ãfunction distance(x1,x2,y1,y2)2ï¼ä½¿ç¨Function()æé å½æ°ï¼è¯·æ³¨æä¸ä¸é¢ç大å°åï¼
var f=new Function*"x","y","return x*y");è¿è¡ä»£ç å建äºä¸ä¸ªæ°å½æ°ï¼è¯¥å½æ°åä½ æçæçè¯æ³å®ä¹çå½æ°åºæ¬ä¸æ¶çä»·ç:
function f(x,y)Functino()æé å½æ°å¯ä»¥æ¥åä»»æå¤ä¸ªå符串åæ°ãå®çæåä¸ä¸ªåæ°æ¶å½æ°ç主ä½ï¼å
¶ä¸å¯ä»¥å
å«ä»»ä½JavaScriptè¯å¥ï¼è¯å¥ä¹é´ç¨åå·åéãå
¶ä»çåæ°é½æ¯ç¨æ¥è¯´æå½æ°è¦å®ä¹çå½¢å¼åæ°åçå符串ãå¦æä½ å®ä¹çå½æ°æ²¡æåæ°ï¼é£ä¹å¯ä»¥åªéç»æé å½æ°ä¼ éä¸ä¸ªå符串ï¼å³å½æ°ç主ä½ï¼å³å¯ã
ãã注æï¼ä¼ éç»æé å½æ°Function()çåæ°ä¸æ²¡æä¸ä¸ªç¨äºè¯´æå®è¦å建çå½æ°åãç¨Function()æé å½æ°å建çæªå½åå½æ°ææ¶è¢«æ为âå¿åå½æ°âã
ããä½ å¯è½é常æ³ç¥éFunction()æé å½æ°çç¨éæ¯ä»ä¹ã为ä»ä¹ä¸è½åªç¨functionè¯å¥æ¥å®ä¹ææçå½æ°å¢ï¼åå æ¯Function()æé å½æ°å
许æ们å¨æå°å»ºç«åç¼è¯ä¸ä¸ªå½æ°ï¼å®ä¸ä¼å°æ们éå¶å¨functionè¯å¥é¢ç¼è¯çå½æ°ä½ä¸ãè¿æ ·å带æ¥çè´é¢å½±åæåºå°±æ¯æ¯æ¬¡è°ç¨ä¸ä¸ªå½æ°æ¶ï¼Function()æé å½æ°é½è¦å¯¹å®è¿è¡ç¼è¯ãå æ¤ï¼å¨å¾ªç¯ä½ä¸æè
å¨ç»å¸¸ä½¿ç¨çå½æ°ä¸ï¼æ们ä¸åºè¯¥é¢ç¹å°è°ç¨è¿ä¸ªæé å½æ°ã
ãã使ç¨Function()æé å½æ°çå¦ä¸ä¸ªåå æ¯å®è½å¤å°å½æ°å®ä¹ä¸ºJavaScript表达å¼çä¸é¨åï¼èä¸æ¯å°å
¶å®ä¹ä¸ä¸ªè¯å¥ï¼è¿ç§æ
åµä¸ä½¿ç¨å®å°±æ¾å¾æ¯è¾çæ¹é¢ï¼çè³å¯ä»¥è¯´ç²¾è´ã
ã3ï¼å½æ°ç´æ¥é
ããå½æ°ç´æ¥éæ¯ä¸ä¸ªè¡¨è¾¾å¼ï¼å®å¯ä»¥å®ä¹å¿åå½æ°ãå½æ°ç´æ¥éçè¯æ³åfunctionè¯å¥é常ç¸ä¼¼ï¼åªä¸è¿å®è¢«ç¨ä½è¡¨è¾¾å¼ï¼èä¸æ¯ç¨ä½è¯å¥ï¼èä¸ä¹æ éæå®å½æ°åãä¸é¢çä¸è¡ä»£ç åå«ä½¿ç¨function()è¯å¥ãFunciont()æé å½æ°åå½æ°ç´æ¥éå®ä¹äºä¸ä¸ªåºæ¬ä¸ç¸åçå½æ°ï¼
å¨JavaScript1.1ä¸ï¼å¯ä»¥ä½¿ç¨æé å½æ°Function()æ¥å®ä¹å½æ°ï¼å¨JavaScript1.2åå
¶åççæ¬ä¸ï¼è¿å¯ä»¥ä½¿ç¨å½æ°ç´æ¥éæ¥æé å½æ°ãä½ åºè¯¥æ³¨æè¿ä¸¤ç§æ¹æ³ä¹é´çéè¦å·®å«ã
ãã
ããé¦å
ï¼æé å½æ°Function()å
许å¨è¿è¡æ¶å¨æå°å建åç¼è¯JavaScript代ç ãä½æ¯å½æ°ç´æ¥éå´æ¯å½æ°ç»æçä¸ä¸ªéæé¨åï¼å°±åfunctionè¯å¥ä¸æ ·ã
ããå
¶æ¬¡ï¼ä½ä¸ºç¬¬ä¸ä¸ªå·®å«çå¿
ç¶ç»æï¼æ¯æ¬¡è°ç¨æé å½æ°Function()æ¶é½ä¼è§£æå½æ°ä½å¹¶ä¸å建ä¸ä¸ªæ°ä¸æ±æ°å¯¹è±¡ãå¦æ对æé å½æ°çè°ç¨åºç°å¨ä¸ä¸ªå¾ªç¯ä¸ï¼æè
åºç°å¨ä¸ä¸ªç»å¸¸è¢«è°ç¨çå½æ°ä¸ï¼è¿ç§æ¹æ³çæçé常ä½ãå¦ä¸ä¸ªæ¹é¢ï¼å½æ°ç´æ¥éæåºç°å¨å¾ªç¯åå½æ°ä¸çåµå¥å½æ°ä¸æ¯å¨æ¯æ¬¡è°ç¨æ¶é½è¢«éæ°ç¼è¯ï¼èä¸æ¯å½éå°ä¸ä¸ªå½æ°ç´æ¥éæ¶ä¹ä¸å建ä¸ä¸ªæ°çå½æ°å¯¹è±¡ã
ããFunction()æé å½æ°åå½æ°ä¹é´éä¹é´ç第ä¸ç¹å·®å«æ¯ï¼ä½¿ç¨æé å½æ°Function()å建çå½æ°ä¸ä½¿ç¨è¯æ³ä½ç¨åï¼ç¸åçï¼å®ä»¬æ»æ¯è¢«å½ä½é¡¶çº§å½æ°æ¥ç¼è¯ï¼å°±åä¸é¢ä»£ç æ说æçé£æ ·ï¼