定义函数
function funname([args]){
//空函数
}
function () {
//匿名空函数
}
//执行效率低,一般当作表达式来用
var fun=new Function([p1,p2,...],body){
//通过构造函数快速生成函数
//p1-ps 为参数
//body 为方法体
}
函数表达式
var a=[1,2,3,4];
//匿名函数
var f=function(arg){
alert(a[2]);
};
f(a);
//完整函数
var f2=function fun(arg){
alert(a[2]);
};
f2(a);
函数嵌套
嵌套的函数只能在函数体内可见,函数外不允许直接调用
function a(){
function b(){
}
}
b();//错误调用
arguments对象
arguments 对象表示参数集合,它是一个伪类数组
function f(){
for(var i=0;i<arguments.lenght;i++){
alert(arguments);
}
}
f(1,2,3)
使用callee 回调函数
arguments对象包含一个callee属性,它引用当前arguments所属的函数,使用该属性可以在函数体内调用函数自身
function f(a,b,c){
var arglen=arguments.lenght;//实参个数
var flen=argument.callee.lenght;//函数形参个数
if(a!=b)
{
throw new Error("传递的参数不匹配")
}
else
{
return a+b+c;
}
}
alert(f(3,4,5))
call() 和apply()是function 对象的原型方法,它们能将特定函数当作一个方法绑定到指定的对象上并调用,调用后并注销该方法
//function.call(thisobj,args...)
//function.apply(thisobj,args)
function a(x,y){
this.z='abc';
return x+y;
}
var b={};
a.call(b,1,2);//返回3
a.apply(b,[2,5]);//返回7
function f(){
a.call(this); //函数f继承a所有属性
return this.z;
}
f(); //返回abc