ES6语法——函数扩展

函数扩展
函数新增特性
  • 参数默认值
  • rest参数
  • 扩展运算符
  • 箭头函数
  • this绑定
  • 尾调用
{
	//函数参数默认值
	//默认值后面,不能有,没有默认值的变量
	//function(x,y=123,z) 这是错误的
	//function(x,y=123,z=444) 这是可以的
	function foo(x, y = 'y的默认值'){
		console.log("默认值",x,y)
	}
	foo(123)//只传一个参数,y就用默认值
	//123 y的默认值
	foo(12,33)//12,33
}
{
	//函数作用域问题
	let x = 100
	function fn1(x,y=x){
		console.log(x,y)
	}
	fn1('hello')// hello hello
	//hello对应的是形参x ;y=x,那么y就是取得前面那个x
	//因为x在函数作用域中已经定义过了,所以y=x中的x就是函数内定义的x
	fn1()//undefined undefined
	function fn2(c,y=x){
		console.log(c,y)
	}
	//因为函数中没有定义过x,那么y=x中的x就是let x = 100
	fn2(200)//200 100
}
{
	//rest参数,rest参数之后不能有别的参数了,因为它在转换参数的时候不知道什么时候截止
	//就是把你的参数转成了数组
	//也就是在你不确定参数的时候,把传入的参数转换成了数组
	function test3(...arg){
		for(let v of arg){
			console.log('rest',v)
		}
	}
	test3(1,2,3,4,'a')
	//1
	//2
	//3
	//4
	//'a'
	function test4(x,...arg){
		for(let v of arg){
			console.log('rest',v,x)
		}
	}
	test4(1,2,3,4,'a')
	//2,1
	//3,1
	//4,1
	//‘a’,1
}
{
	//扩展运算符
	//可以理解为扩展运算符是rest参数的逆运用
	console.log(...[1,2,4])//1,2,4 //把数组拆成了离散值
	//rest参数是把参数转成数组
	console.log('a',...[1,2,4])//a,1,2,4
}
{
	//箭头函数
	let arrow = v => v*2;//定义arrow是函数
	let arrow1 = () => 10;//没有参数的箭头函数
	//函数名
	//前面是参数 (v是参数)
	//后面是返回值
	console.log(arrow(3))//6
	console.log(arrow1())//10
}
{
	//尾调用,出现在函数编程里,也就是说,函数的最后一句话,是不是一个函数
	//尾调用提升性能
	function tail(x){
		console.log(x)
	}
	function fx(x){
		return tail(x);
	}
	fx(123)//123
	//这就是尾调用
}

做箭头函数的时候一定要注意this绑定
尾调用的好处有哪些?
递归是函数嵌套相当耗费资源,可以用尾调用做优化

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章