ES6引入rest参数(形式为...变量名),用于获取函数的多余参数,这样就不需要使用arguments对象了;
//arguments变量的写法
function sortNumbers(){
return Array.prototype.slice.call(arguments).sort();
}
//rest参数的写法
const sortNumbers = (...numbers) => numbers.sort();
arguments对象不是数组,是类似数组的对象;
Array.prototype.slice.call(arguments)先将arguments转为数组;
而rest参数就不存在这个问题,rest参数是真正的数组;
注意:rest参数之后不能再有其他参数,必须是最后一个参数,否则报错;
//利用rest参数改写数组push方法
function push( array, ...items ){
items.forEach(function(item){
array.push(item);
console.log(item);
});
}
var a = [];
push(a, 1, 2, 3);
函数的name属性,返回该函数的函数名;
function foo(){}
foo.name //foo
如果将一个匿名函数赋值给一个变量,ES5的name属性会返回空字符串,而ES6的name属性会返回实际的函数名;
var f = function() {};
f.name //ES5 ""
f.name //ES6 "f"
如果将一个具名函数赋值给一个变量,ES5和ES6的name属性都返回这个具名函数原本的名字;
var f = function bar() {};
f.name //ES5 "bar"
f.name //ES6 "bar"
Function构造函数返回的函数实例,name属性的值为anonymous;
(new Function).name //"anonymous"
bind返回的函数,name属性值会加上bound前缀
function f() {};
f.bind({}).name //bound f
(function(){}).bind({}).name //bound