重载
函数不定参
js传不定参,函数内部有一个arguments对象,接收传递过来的参数
arguments对象是一个类数组对象
function go(a){console.log(arguments);console.log(a);console.log(arguments[1]);}go(10,12)
重载:**就是根据参数的不同,动态决定调用哪个方法
js中没有重载的概念,因为重复声明,下面的会覆盖上面的**
//js中没有重载的概念,因为重复声明,下面的会覆盖上面的function go(a){console.log(a);}function go(a,b){console.log(a+b);}
使用arguments对象模拟重载
function go(){if(arguments.length==1){console.log(arguments[0]);}else if(arguments.length==2){console.log(arguments[0]+arguments[1]);}}go(1)go(10,20)
递归
函数调用函数自身,就叫递归
<script>function show(){setTimeout(function(){console.log(1)show();},1000)}show()</script>
回调函数
回调函数:就是将函数作为参数,传递给另一个函数
场景:一般在异步调用中使用
作用:
1.将函数内部的值返回到外部
2.取代了return语句
<script>var show = function(res){console.log(res);}function go(callback){var a = 10;callback(a);}go(show);</script>
默认赋值
当函数内中参数大概率不会发生改变时,可以使用默认赋值
<script>function go(method="get"){console.log(method)}go();//getfunction ajax({url,method = "get"}){console.log(method);console.log(url)}ajax({url:"xxx"})//get <br> xxx</script>
