1. 函数定义
使用关键字function来声明;
function 函数名(参数1, 参数2, ... )
{
语句块
return 返回值; //不是必须
}
return也可以不带返回值,函数在停止执行后将返回undefined值,这种做法一般用在需要停止函数运行而又不需要返回值的情况下;
2. 函数参数
ECMAScript函数的参数与其他语言相比有极大的不同;
1)ECMAScript不会介意传递进来多少个参数,也不在乎传递进来的参数是什么类型,即使定义函数时只有两个参数,可以传递进来一个、两个或者多于两个;当传递进来的参数少于定义的参数时,没有传递值的参数就是undefined;
本质:ECMAScript中调用函数时传递的参数值是用一个数组表示的,函数体内可以通过arguments对象来访问这个参数数组,比如arguments[0]是第一个元素,arguments[1]是第二个元素.等等;
通过argumengts的属性length属性可以得到有多少个参数传递给了函数;
function detectArgument(arg1, arg2)
{
document.write(arguments.length+"<br>");
document.write(arg1+"<br>");
document.write(arg2+"<br>");
}
detectArgument(10, 20); //2 10 20
detectArgument(30); //1 30 undefined
detectArgument(40, 50, 60); //3 40 50
//使用arguments对象访问传递的参数
function detectArgument() //没有定义参数
{
for(var i=0; i<arguments.length; i++)
{
document.write(arguments[i]+"<br>");
}
}
detectArgument(10, 20); // 10 20
arguments的值与相对应的参数的值保持同步,如下代码:
function detectArgument(arg1, arg2)
{
document.write(arg1+"<br>"); // 输出10
document.write(arg2+"<br>"); // 输出20
//改变arguments[1]的值,与之对应的参数arg2也发生改变
arguments[1]=100;
document.write(arg2+"<br>"); //输出100
//改变参数arg1的值,与之对应的arguments[0]也发生改变
arg1=200;
document.write(arguments[0]); //输出200
}
detectArgument(10, 20); //相当于arguments[0]=10, arguments[1]=20
严格模式对如果使用arguments对象做了一些限制,重写arguments的值会导致语法错误;
3. 没有重载
在其它语言中,可以为一个函数编写两个定义,只要这两个定义的参数的类型或者数量不同即可,但是由于ECMAScript的函数调用时不限制传入参数值的类型和数量,所以不能重载;