当前位置: 首页 > 图文教程 > 网络编程 > Javascript > 如何实现JS函数的重载

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 中的 如何实现JS函数的重载


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 173 ::
收藏到网摘: n/a

javascript不能支持函数的重载,如下:
复制代码 代码如下:

<script language="JavaScript">
function f(length)
{
alert("高为:"+length);
}
function f(length,width)
{
alert("高为:"+length+",宽为:"+width);
}
</srcipt>

上面那段代码其实是行不通的,因为函数定义时的参数个数和函数调用时的参数个数没有任何关系。 在函数中可以用f.arguments[0]和f.arguments[1]得到调用时传入的第一和第二个参数,所以定义function(length),后面用f(10,10)调用是没有问题的。所以在上面这段代码中,第二个函数是永远不可能被调用到的,那么,要怎样才能实现像函数重载那样的功能呢?
那就是在函数定义中用f.arguments.length判断一下调用时传入的参数个数。然后对不同的情况采用不同的处理方式。
如下:
复制代码 代码如下:

<script language="JavaScript">
function f()
{
var len= arguments.length;
if(1 == len)
{
var length = arguments[0];
var width = arguments[1];
f2(length,width);
}
else
{
var length = arguments[0];
f1(length);
}
}
function f1(length)
{
alert("高为:"+length);
}
function f2(length,width)
{
alert("高为:"+length+",宽为:"+width);
}
</srcipt>

这样,你就可以给函数f()传入一个参数也可以传入两个参数了,比如f(10)和f(10,10);
个人觉得,这样虽然可以实现重载,但也不是很好用,我们可以根据具体情况在一个函数中实现重载,如果要重载的两个函数相差较大,那就保留两个函数,而如果两个函数的实现基本差不多,那么可以在一个函数中进行判断,处理不同的部分,而不需要像上面那样写成三个函数,如下:
复制代码 代码如下:

<script language="JavaScript">
function f(length)
{
var len= arguments.length;
if(1 == len)
{
var width = arguments[1];
alert("高为:"+length+",宽为:"+width);
}
else
{
alert("高为:"+length);
}
}
</srcipt>