es6 --函数的扩展

版权声明:版权声明:本文为博主原创文章,若文章中有错误请联系博主改正,请不要恶意留言(不喜欢请绕道)。欢迎大家转载 https://blog.csdn.net/qq_37674616/article/details/83039972

一、函数参数默认值

//es6之前的做法
function log(x,y){
    var y=y||'world';
    console.log(x,y);
}
log('hello'); // hello world
log('hello',0); //hello world

**:这种写法 当参数y赋值为false时,此时默认值就有效。这可能并不是我们想要的。 你可能会做如下改进:

function log(x,y){
    if(arguments.length==1){
        y='world';
    }
    console.log(x,y);
}

让我们感受下es6的写法:

function log(x,y='world'){
    console.log(x,y);
}
log('hello','cc'); // 'hello cc'
log('hello',0); //'hello 0'

 2.与解构默认值结合使用

此时我们一定要传入对象,不传则就会报错。

function log({x,y=5}){
    console.log(x,y);
}
log({}); //undefiend 5
log({1,2}) // 1 2
log(); //报错 

3.作用域

 如果参数默认值是一个变量,则该变量所处的作用域与其他变量的作用域规则是一样的,即先是当前函数的作用域,然后才是全局的作用域。

var x=1;
function f(x,y=x){
    console.log(y);
}
f(2); //2

//如果调用时函数作用域内部的变量x没有形成。

let x=1;
function f(y=x){
    let x=2;
    console.log(y);
}
f(); //1

二、rest参数

形式如(... 变量名)用于获取函数的多余参数。将多余的参数放到一个数组中。

function add(...values){
    let sum=0;
    values.forEach(function(item){
        sum+=item;
    });
    return sum;
}
add(2,3,5);

三、扩展运算符

扩展运算符是三个点(...)。

//数组转换数值

console.log(1,...[2,3,4],5);

代替apply方法

//求最大值 在es5中的写法
Math.max.apply(null,[12,19,22]);

//es6
Math.max(...[12,19,22]);

//转换类数组对象

var nodeList=document.getElementsByTagName('div');
//es5
var arr=Array.prototype.slice.apply(null,nodeList);

//es6
var arr1=[...nodeList];
var arr1=[1,2];
var arr2=[3,4,5];
var arr3=[19,21,22];

//es5中
arr1.concat(arr2,arr3);

//es6中
[...arr1,...arr2,...arr3]

四、箭头函数

1.箭头函数一般用于回调中,this指向外层函数。

2.不可以当作构造函数。不能使用new命令。

3.不可以使用arguments对象。该对象在函数体内不存在。

4.不能用作Generator函数

//用于回调函数中  es5

var arr=[1,2,3,4,5];
arr.some(function(item){
    return item>0;
});

//es6
arr.some((item)=>{return item>0;})

this总指向外层函数。 

		var handle={
			id:0,
			init:function(){
				console.log('init',this.id++);
				return ()=>{
					console.log('箭头函数 this',this.id);
				}
			}
		}
		handle.init()();

 自身没有arguments,super

function foo(){
    setTimeout(()=>{
        console.log('arguments:',arguments);
    },1000);

}
foo(1,2,34,2);
//arguments: [1,2,34,2]

猜你喜欢

转载自blog.csdn.net/qq_37674616/article/details/83039972