JavaScript的函数定义有三种方式:
1、基本语法
function 函数名(参数){}
2、使用表达式
函数名(变量)=function(参数){};
3、使用Function对象的构造器(不建议)
函数名(变量)=new Function(参数...);
函数可自调用:
(匿名函数定义)();
函数的调用方式(this关键字的指代):
1、直接作为全局函数调用,此时this关键字指代全局对象,在浏览器中是Window对象。
2、函数作为对象的方法调用,此时this关键字指代该对象。
3、函数作为构造函数,调用该函数用于创建对象,则该函数里的this关键字指代具体创建时的对象。
4、函数本身是一个对象,它有两个调用方法call和apply,这两个方法接收的第一个参数将作为函数this关键字的指代对象。
//declare function
//1.base
function max(a,b){
return a>b ? a : b;
}
//2.function expression
min=function(a,b){
return a<b ? a : b;
};
//3.use function contructor
add=new Function("a","b","return a+b");
document.write(max(3,5),"</br>");
document.write(min(3,5),"</br>");
document.write(add(3,5),"</br>");
//function can look as a value and use in a expression
var x=3*add(4,5);
document.write("3*(4+5)=",x,"</br>");
fun=function(){return;};
var num=3+fun();
document.write(num,",",fun(),"</br>");//NaN,undefined
//function call itself
(function(){document.write("hi,i'm a function!</br>");})();
//actually function is object
(function(a,b){document.write(arguments.length,",",arguments[0],",",arguments[1],"</br>");})();
document.write(add.toString(),"</br>");
//set a default argument
function max(a,b){
a=a || 10;
b=b || 0;
return a>b ? a : b;
}
document.write(max(),"</br>");
//this keyword in function
function foo1(){
//this is the global object
document.write(this,"</br>");
}
foo1();
var myObject={
"firstName":"lin",
"secondName":"jin",
//this is myObject
fullName:function(){
return this;
}
}
document.write(myObject.fullName(),"</br>");
function foo2(arg1,arg2){
//this is the p
this.firstName=arg1;
this.lastName=arg2;
}
var p=new foo2("John","Ann");
document.write(p.firstName,"</br>");
function foo3(a,b){
//this is myObject
document.write(this,",","a*b=",a*b,"</br>");
}
foo3.call(myObject,3,4);
foo3.apply(myObject,[4,5]);
函数闭包:
如果我们想要实现一个计数器的函数,我们可以将计数个数声明为全局变量,然后函数内部进行累加,如下
var counter=0;
function add(){counter++;}
但因为counter是一个全局公有变量,在程序的任何地方都可以对它进行修改,这显得很不安全。
另一种想法是将counter定义在函数内部,但每次调用计数函数的时候都会对counter进行初始化,根本做不到计数的效果。
function add(){var counter=0;counter++;}
这时候,我们就得用到函数闭包了,闭包的基础是函数内部嵌套函数,内层函数可以访问外层函数的局部变量,使其成为自己的私有变量。这样我们只需要执行外层函数一次,对计数个数进行初始化一次,然后返回内层函数,此时内层函数就已经有一个初始化好的私有变量,之后调用这个内层函数即可。
//function closure
var add=(function(){
var counter=0;
return function(){return ++counter;}
})();
document.write(add(),"</br>");
document.write(add(),"</br>");
document.write(add(),"</br>");