直接看下面的代码!
javascript代码中有3个hello函数,函数名相同,但是参数列表不同,3个按钮的点击事件,经过测试,alert弹出的都是带2个参数的,后来我将这3个同名的函数,调换了顺序位置,发现一个规律,这3个同名的重载方法,哪个方法在最后,那3个按钮的点击事件不管是调用无参hello函数还是调用1个参数的hello函数还是调用2个参数的hello函数,都是调用的最后一个顺序位置的hello函数,可见javascript中的方法重载是跟方法出现的顺序位置有关系,我这样理解不知道对不对!
请大家说说自己的理解和自己知道的javascript重载的知识点!以前我也一直没注意javascript中方法重载的这个问题!
<html>
<head>
<meta charset="UTF-8">
<title>javascript中的方法重载的疑惑?</title>
<script type="text/javascript">
function hello() {
alert("我是无参数的hello()函数!");
}
function hello(userName) {
alert("我是带1个参数的hello(userName)函数!" + " - " + userName);
}
function hello(userName, age) {
alert("我是带2个参数的hello(userName, age)函数!" + " - " + userName + " - " + age);
}
</script>
</head>
<body>
<div align="center">
<h2>javascript中的方法重载的疑惑?</h2>
<input type="button" value="js方法重载(1个参数)" onclick="hello('令狐冲')">
<input type="button" value="js方法重载(2个参数)" onclick="hello('韦小宝', 16)">
<input type="button" value="js方法重载(无参数)" onclick="hello()">
</div>
</body>
</html>