函数调用时的奇怪行为 [英] Strange behavior on function calling

查看:52
本文介绍了函数调用时的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在调用Javascript函数时,即使我具有相同的函数名称,但JS似乎都优先考虑不带参数的函数.奇怪的行为仅在以下情况下发生:

When calling a Javascript function, it seems like JS gives priority to functions without parameters first, even if I have the same function name with parameters. The strange behavior only happens in the following scenario:

我有一个带有嵌入式Javascript的HTML页面,如下所示:

I have a an HTML page with embedded Javascript, like this:

 //Javascript in the page  
 function testAbc(){
       alert('testAbc no params');
 }

 //Javascript in common.js
 function testAbc(x){
      alert('testAbc with param:'+x);
 }
 function testAbcFunc(x){
      testAbc(x);
 }

现在从页面中的某处开始,我从common.js调用 testAbcFunc ,希望它使用具有通用功能的参数调用 testAbc .但是奇怪的是,JS在没有参数的情况下在原始页面中调用了该函数!

Now from somewhere in the page, im calling testAbcFunc from the common.js expecting it to call testAbc with parameter which is the common function. But strangely, JS calls back the function in the original page without params!!

我已经调试该错误了几个小时了,我尝试了这段简短的代码来重现该错误,每次都会发生.

I have been debugging this bug fore few hours now, and i tried this short code to reproduce the bug, it does happen each time.

注意:如果所有函数都在同一个页面中,则将调用正确的函数(带有params),但是当它们在页面和JS文件之间分割时.JS似乎优先于页面中的功能,即使它没有参数

NOTE: if all functions are in the same page, the correct function (with params) will be called, but when ther are split between the page and the JS file. JS seems to give priority to the function in the page even though is doesn't have parameter

推荐答案

JavaScript没有重载功能.它不在乎签名,它仅通过名称调用函数,而没有别的.奇怪的是,后来的功能并未完全隐藏第一个,但是好吧,关于这种行为没有任何规范.

JavaScript doesn't have overloaded function. It doesn't care about signatures, it calls functions solely by names and nothing else. It is strange that later function does not completely hide the first one but well, there's no spec about that behaviour.

所以不要这样做,请在函数内使用 arguments.length 检查参数的数量,并且不要尝试使用将永远无法工作的重载.

So just don't do that, check the number of params with arguments.length inside the function and don't try to use overloading which will never work.

function testAbc(){
   if (arguments.length == 0) {
       alert('testAbc no params');
   } else {
       var x = arguments[0];
       alert('testAbc with param:'+x);
   }
}

这篇关于函数调用时的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆