在javascript中函数非常重要,节约了代码量,提升代码复用率。话不多说,先定义几个要点再一一说明;
1、函数的类别的定义
在jvascript里函数有系统内置函数和自定义函数,系统函数是不需要程序员编写即可调用的函数,如tostring。自定义函数是指程序员通过关键字function编写的函数;
函数定义:
function test(){alert('我是无入参无出参的函数test');};
function test1(a,b){ alert('我是无出参有两个入参的函数test1,入参a:'+a+',入参b:'+b+'');};
function test2(){return 1;} //带有出参的函数
function test3(a,b){return a+b;} //带有入参的和出参的函数
函数若有入参是不需要给入参指定数据类型;
2、函数表达式
javascript函数可以赋值给变量,这种方式称之为函数表达式。函数表达式和普通函数在系统解析方式上会有不同,系统解析函数表达式是必须执行到表达式申明那一行后才记录和识别该表达式,解析普通函数是优先对声明进行记录,即调用函数的语句在申明函数前照样能正常执行,而函数表达式则不行。例:
console.log(fun(1,2)); //执行会报错
var fun=function(a,b){
return a+b;
}
console.log(fun(1,2)); //输出为3
再看个例子:
console.log(funs(2,3)); //输出5
function funs(a,b){
return a+b;
}
3、函数的嵌套
在javascript里允许对函数进行嵌套。例:
function test1(x){
var t1=0;
function test2(z){
console.log(z);
function test3(){
console.log(t1);
}
test3();
}
var z=x+y;
test2(z);
test3(); //会报test3 is not defined
}
函数嵌套需要注意的是:
被嵌套的函数的作用域不会超过父级作用域,如上面test2只能在test1里调用;
被嵌套的函数内可以访问父级函数的变量值;如test3可以访问到test1函数的t1变量但是在test1函数代码块里却不能直接访问test3;
4、匿名函数
匿名函数是定义时候无需给予名称且不会像其他函数一样定以后可以通过表达式进行调用;
定义:
(function(){
console.log(“我就是无参匿名函数呀!”);
});//这里是定义了,但是实际上不会执行…
(function(){
console.log(“我就是无参匿名函数呀!”);
}()); //这里是定义了,且会执行。因为在函数结尾后加入了()表示立即执行
如果匿名函数是有入参则在最后的()里需要传入参值:
(function (x, y) {
console.log("我就是匿名函数啊~");
console.log("x:" + x);
console.log("y:" + y);
}(1,2))
5、arguments对象
Javascript中提供了一个Arguments对象,该对象可以获取从Javascript代码中传递过来的参数,并将这些参数存储在arguments[]数组里,可以针对这一特性可在代码中检测参数的个数、输出参数值;
function sayhi(){
if(arguments[0]==“bye”){
return;
}
alert(arguments.length);
}
6、prototype属性
Javascript给每一个对象都添加了一个prototype属性。通过这个属性程序员可以访问到对象所指向的原型,并且通过该属性javascript允许程序员对原型新增方法和属性!且新增完属性和方法后已根据此原型实例化的对象都可共享此方法和属性。
例:
function Person(name, gender)
{
this.name = name;
this.gender = gender;
this.whoAreYou = function(){
var res = "I'm " + this.name + " and I'm a " + this.gender +".";
return res; };
}
// 通过prototype给Preson原型新增属性和方法
Person.prototype.age = 24;
Person.prototype.getAge = function(){
return this.age;
};
var fun = new Person("Tower", "male");
alert(fun.name);
alert(fun.gender);
alert(fun.whoAreYou());
alert(fun.getAge()); //对象可以使用通过prototype创建的原型方法
//继续通过prototype对象给原型新增属性以及方法
Person.prototype.salary = 10000;
Person.prototype.getSalary = function () {
return this.name + " can earn about " + this.salary + "RMB each month."; }
//实例化了对象后根据prototype生成的属性和方法后 fun可以调用这些方法和属性
alert(fun.getSalary());
alert(fun.constructor.prototype.age);
Person.prototype.age
alert(Person.prototype.age);
可以通过prototype的特性进行原型之间的克隆,例:
function baseclass(){
this.showMsg=function(){
alert(“baseclass::showMsg”);
}
}
function extendclass(){
}
extendclass.prototype=new baseclass();
var instance=new extendclass();
instance.showMsg();
如果对象本身已存在和克隆对象相同名的属性或方法则不会克隆那个属性和方法
function baseclass(){
this.showMsg=function(){
alert(“baseclass::showMsg”);
}
}
function extendclass(){
this.showMsg=function(){
alert(“extendclass::showMsg”);
}
}
extendclass.prototype=new baseclass();
var instance=new extendclass();
instance.showMsg();