//展现结果 function showResult(result) { var showDiv = document.getElementById('result'); showDiv.innerHTML = ''; showDiv.innerHTML = result; }; //展现结果2 function showResult2(result) { var showDiv = document.getElementById('result2'); showDiv.innerHTML = ''; showDiv.innerHTML = result; }; //展现结果3 function showResult3(result) { var showDiv = document.getElementById('result3'); showDiv.innerHTML = ''; showDiv.innerHTML = result; }; //测试同名方法 function testFun() { showResult('this is a function named \'testFun\' with no arguments.'); }; function testFun(arg) { showResult('this is a function named \'testFun\' with one argument,the argument is '+arg); }; //2th测试,交换两个函数的顺序 //测试同名方法 function testFun2(arg) { showResult2('this is a function named \'testFun2\' with one argument,the argument is '+arg); }; function testFun2() { showResult2('this is a function named \'testFun2\' with no arguments.'); }; //3th测试,测试覆盖,同名同参数 function testFun3() { showResult3('this is a function named \'testFun3\' first.'); }; function testFun3() { showResult3('this is a function named \'testFun3\' second.'); }; //-->
2th test
3th test
首先按名为 function with no arguments 的按钮
页面的结果为 this is a function named 'testFun' with one argument,the argument is undefined 然后按名为 function with one argument test 的按钮 页面的结果为 this is a function named 'testFun' with one argument,the argument is test 然后按名为 function with no arguments 的按钮 页面的结果为 this is a function named 'testFun2' with no arguments. 然后按名为 function with one argument test 的按钮 页面的结果为 this is a function named 'testFun2' with no arguments.
从以上的测试中我们发现我们只是点换了两个函数的定义顺序,结果大不相同。 从上面的测试中我们可以得出结论: 重载的话,只要函数定义在下面就会覆盖上面的函数定义。 好了,接下来看覆盖。 按名为 test function share the same name and arguments. 的按钮
页面的结果为 this is a function named 'testFun3' second. 测试结果很明显,结论也是和上面相同的。 最终,我们得出结论: 方法重名,JS会以最后定义的函数作为函数体。当然这不包括JS中的继承中的覆盖。 欢迎拍砖