一、函数的 length 属性数组
ES6 容许为函数的参数设置默认值,即直接写在参数定义的后面。函数
function test(x, y = 'World') { console.log(x, y); }
注意:函数的length属性,将返回没有指定默认值的参数个数。若是遇到有默认值的参数 就中止。this
function test(x, m,y = 'World',z,f) { ... } console.log(test.length) // 2 遇到默认参数则中止 因此为2
二、rest参数spa
ES6引入rest参数,用于获取函数的多余参数,这样就不须要使用arguments对象了。rest参数搭配的变量是一个数组,该变量将多余的参数放入数组中;rest
...values 就是 rest 参数的表现形式
function add(...values) { console.log(values); } add(2, 5, 3)
三、箭头函数code
ES6 中容许使用“箭头”(=>)声明函数对象
基本用法:blog
let fun = val=>val; //一个参数val并返回一个val // 等价于 function fun(val){ return val; }
注意:io
若是箭头函数不须要参数或须要多个参数,就使用一个圆括号表明参数部分;console
若是箭头函数的代码块部分多于一条语句,就要使用大括号将它们括起来,而且 使用return语句返回。
let fun = (name,age)=>{ console.log('姓名'+name); console.log('年龄'+age); }
箭头函数有内部属性arguments,但不保存实参
四、箭头函数的 this 指向
箭头函数里面没有本身的this,天然而然也就不能做为构造函数,箭头函数是引用外层的this。在箭头函数中 this 指向是固定的。
箭头函数致使this
老是指向函数定义生效时所在的对象中的this;
function foo() { setTimeout(() => { console.log(this); }, 100); } foo() // global 对象 ,由于箭头函数没有本身的this,foo函数的this就是箭头函数this的指向。foo中this指向是global 因此 箭头函数中的this也是指向global(即外层this)
eg:
function foo() { setTimeout(() => { console.log('id:', this.id); }, 100); } var id = 21; foo.call({ id: 42 }); // 更改foo中this指向对象{id:42} 因此打印结果为42;