1.1函数参数的默认值
es6之前,不能直接为函数参数提供默认值,只能采用变通的方法
//es5写法
function log(x,y){
if(typeof y === 'undefined'){
y = 'world';
}
y = y || 'world';
console.log(x,y);
}
log('hello'); //hello world
log('hello','tom'); //hello tom
log('hello',''); // hello world
//es6写法
function log(x = 0, y = 'world') {
console.log(x,y);
}
log('hello');//hello world
log('hello',''); // hello
log('hello','lily'); // hello lily
//这样写的好处是: 方便以后阅读和维护,可以意识到哪些参数是可以省略的;有利于代码的优化,即使未来的版本在对外接口中彻底拿掉这个参数,也不会对原版本有任何影响
1.2 参数默认值的位置
通常情况下,定义了默认值的参数,应该是函数的尾参数,如果是非尾部的参数设置默认值,这个参数是没有办法省略的
function f(x = 1,y,z){
return [x,y,z];
}
f();//[1,undefined,undefined]
f(,1,1); //报错
指定了默认值以后,函数的length属性将返回没有指定默认值的参数个数(也就是说指定了默认值后,lengthsh)
- 与解构默认值相结合
function fetch(url,{body = '',method = 'GET',headers = {}} = {}){
console.log(method);
}
fetch('http://www.baidu.com');//GET
fetch('http://www.baidu.com',{});//GET
fetch('http://www.baidu.com',{body : '111', method : 'POST', headers : {}}); //POST
- rest 参数,形式为(…变量名),用于获取函数的多余参数,这样就不需要arguments 对象了。rest参数搭配的变量是一个数组,该变量将多余的参数放入数组中
function add(...values){
let sum = 0;
for(var val of values){
sum += val;
}
return sum;
}
add(2,5,6); //13
//与arguments不同的是,arguments对象不是数组,而是类似数组的对象,如果需要使用数组的方法,必须使用Array.prototype.slice.call 想将其转为数组,rest它就是一个真正的数组,数组的特有方法它都可以使用,注意的是rest参数之后不能再有其他参数,只能是最后一个参数,否则会报错
- name属性:函数的name属性,返回该函数的函数名
function add(...values){
let sum = 0;
for(var val of values){
sum += val;
}
return sum;
}
add(2,5,6); //13
console.log(add.name);
var fn = function(){
console.log('我是函数fn');
}
console.log(fn.name);
- 箭头函数
5.1 基本用法
var f = v => v;
f(5); //5
上面的箭头函数相当于
function f(v){
return v;
}
5.2 箭头函数不需要或者需要多个参数,就使用一个圆括号代表参数部分
var f = ()=> 'hello';
等同于
var f = function (){ return 'hello' }
var sum = (num1,num2) => { num1 + num2}
等同于
var sum = function(num1,num2){ return num1 + num2}
5.3 如果箭头函数需要向外返回一个对象,必须在对象外面包裹一层括号(对象的大括号可能被解释为代码块)
var obj = id => ({id : id, name : 'temp'});
console.log(obj('111')); //{id : 111,name : 'temp'}
箭头函数的另一个好处是简化回调函数
function f(count){
let timer = setInterval(()=>{
console.log(count++);
},1000)
}
f(3)
5.4 箭头函数的this指向问题
函数体内的this对象,就是定义时所在的对象而不是使用时所在的对象
function foo(){
return ()=>{
return ()=>{
return ()=>{
console.log('id' + this.id);
}
}
}
}
var f = foo.call({id : '222'});
f()()(); // 222
f().call({id : '333'})(); //222
f()().call({id : '444'}); //222
//上述代码中只有一个this,就是foo的this,所以输出结果都一样,因为所有的内层函数都是箭头函数,都没有自己的this,它们的this 都指向foo函数的this
var id = 21;
function foo(){
setInterval(()=>{
console.log(this.id); // 1
},1000)
}
foo.call({id : 1});
function fetch(){
setInterval(function(){
console.log('id:' + this.id);
},100)
}
fetch.call({id : 2});//id:21
//真正执行到100毫秒之后,this指向window,所以输出为21,而箭头函数this总是指向函数定义生效时所在的对象
箭头函数可以让this指向固定化,这种特性很有利于封装回调函数;this指向的固定化并不会因为箭头函数内部有绑定this的机制,实际原因是箭头函数根本没有自己的this,导致内部的this就是外层代码块的this,正因为它没有this,所以也就不能用作构造函数
转载链接【http://es6.ruanyifeng.com/#docs/function】