开发者

Strange behavior on function calling

When calling a Javascript function, it seems like JS gives priority to functions withou开发者_如何转开发t parameters first, even if I have the same function name with parameters. The strange behavior only happens in the following scenario:

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);
 }

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.

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 does not support method overloading based on parameters. It simply uses the last-defined function if multiple functions have the same name. The version in the page will override the included version. When it worked for you, I assume that the include version (with the argument signature) was inlined after the original.


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.

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);
   }
}


There is no function overloading in JavaScript. If you are defining a function with two times with diffrent number of parameters the last one to be defined will be called.

Also, you should be namespacing your JavaScript.

Like so:

var common = {
    testABC: function () {
        //Stuff
    }
};

Then call testABC like this

common.testABC();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜