手机
当前位置:查字典教程网 >编程开发 >Javascript教程 >js 覆盖和重载 函数
js 覆盖和重载 函数
摘要:学过JAVA的人对函数的覆盖和重载肯定是再熟悉不过了。重载指两个或多个函数的参数类型,顺序和数量以及返回值不一样。覆盖指两个或多个函数的参数...

学过JAVA的人对函数的覆盖和重载肯定是再熟悉不过了。

重载指两个或多个函数的参数类型,顺序和数量以及返回值不一样。

覆盖指两个或多个函数的参数类型,顺序和数量以及返回值完全一样。

那javascript真的有这种特性么?

回答是JS中函数重名只会采用最后一个定义。

首先来看下下面的代码

复制代码 代码如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>

<HEAD>

<TITLE> New Document </TITLE>

<META NAME="Generator" CONTENT="EditPlus">

<META NAME="Author" CONTENT="">

<META NAME="Keywords" CONTENT="">

<META NAME="Description" CONTENT="">

</HEAD>

<SCRIPT LANGUAGE="JavaScript">

<>

</SCRIPT>

<BODY>

<div>

<input type='button' onclick='testFun();' value='function with no arguments'/></br>

<input type='button' value='function with one argument test'/>

</div>

<div id="result"></div>

<hr>2th test <hr>

<div>

<input type='button' onclick='testFun2();' value='function with no arguments'/></br>

<input type='button' value='function with one argument test'/>

</div>

<div id="result2"></div>

<hr>3th test <hr>

<div>

<input type='button' onclick='testFun3();' value='test function share the same name and arguments.'/></br>

</div>

<div id="result3"></div>

</BODY>

</HTML>

首先按名为 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中的继承中的覆盖。

欢迎拍砖

【js 覆盖和重载 函数】相关文章:

javascript中动态函数用法

音乐播放用的的几个函数

js获取变量

jquery预加载图片的方法

javascript瀑布流式图片懒加载实例

javascript函数特点实例

一个表格收缩展开的函数

总结一些js自定义的函数

js控制网页前进和后退的方法

jQuery 遍历函数详解

精品推荐
分类导航