第五章
函数的调用
普通函数
命名函数
函数名();
function add(){ }
add();
匿名函数
第一种:赋值变量
var add=function (){
}
add();
第二种:直接调用 1
(function(){
})();
-
(function(){ }());
+-!function(){
}();
递归调用

方法的调用
var la={
add:function(num1,num2){
return num1+num2;
}
sub:function(num1,num2){
return num1-num2;
}
}
la.add(2,3);
document.onclick=function(){
console.log('你点击了文档');
};
document.onclick();
-
不合法字符
'@':function(){ console.log('@'); } console.log(la['@']())
var key='add';
console.log(la.[key](1,2);
链式调用
$('p').html('段落').css('background-color','red')....;
构造函数(首字母大写)
直接调用:new '函数名();'
间接调用call与apply
第一个参数是改变this
的值
区别:call
将参数一个一个传,apply
是通过数组来传递
例子:
function add(num1,num2){
return num1+num2;
}
console.log(add(1,2));
console.log(add.call(window,1,2));
console.log(add.apply(window,[1,2]));
结果相同:

第六~七章
参数个数:
例子:
<script type="text/javascript">
function pow(b,p){
//if(!p) p=2;
p=p||2;
return Math.pow(b,p);
}
console.log(pow(2,6));
</script>
arguments(类数组)
arguments对象是一个伪数组对象,它有length
属性,可以arguments[i]
来访问对象中的元素,但它不能用数组的一些方法,例如push,pop,slice
等。
可传递任意个参数
arguments
的length
属性
表示function
函数实际所传参数的个数。函数名点length
可以获取函数期望的传参个数。
可以用arguments[i]
来访问函数所传的参数。
例子
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
function add(){
if (arguments.length==0) return;
var sum=0;
for(var i=0;i<arguments.length;i++)
{
sum+=arguments[i];
}
return sum;
}
console.log(add());
console.log(add(1,2,3,4,5));
</script>
</body>
</html>
结果:


每个函数都自带length属性
arguments.callee
调用
arguments
的callee
属性可以调用函数本身
当函数正在执行时才可调用,可以实现方法的递归调用。
注意:严格模式下不能用arguments.callee
例子:
1.阶乘
function la(num){
if (num<=1) return 1;
return num*arguments.callee(num-1)
}
console.log(la(5));
function la(a,b,c){
var e = arguments.callee.toString();
console.log(e);
}
la(); //打印出函数本身
什么可以作为参数
- 什么都不传
- 数字
- 字符串
- 布尔值
- undefined
- null
- 数组
- 对象


用对象作为参数,传参可以不按顺序
9.函数
什么可以作为返回值
return作用:
返回一个值
结束循环
-
什么都不传
-
数字
-
字符串
alert([1,2,3].toString());
将前面的数组转换城字符串 -
布尔值
-
undefined
-
null
-
数组
-
对象
-
函数:为了写出更好更优雅的函数,会将函数作为参数传递到另一个函数中,组成一个新功能函数