一丶ES6 容许为函数的参数设置默认值,即直接写在参数定义的后面。javascript
function log(x, y = 'World') { console.log(x, y); } log('Hello') // Hello World log('Hello', 'China') // Hello China log('Hello', '') // Hello
二丶与解构赋值结合java
function fetch(url, { body = '', method = 'GET', headers = {} }) { console.log(method); } fetch('http://example.com', {}) // "GET" fetch('http://example.com') // 报错
三丶做用域函数
一旦设置了参数的默认值,函数进行声明初始化时,参数会造成一个单独的做用域(context)。等到初始化结束,这个做用域就会消失。这种语法行为,在不设置参数默认值时,是不会出现的。(做用域就在参数的这个小括号里面)fetch
var x = 1; function f(x, y = x) { console.log(y); } f(2) // 2
let x = 1; function f(y = x) { let x = 2; console.log(y); } f() // 1
四丶 rest 参数this
function add(...values) { let sum = 0; for (var val of values) { sum += val; } return sum; } add(2, 5, 3) // 10
五丶箭头函数url
1.只有一个参数时能够省略小括号,,,函数语句只有一句能够胜率大括号,如spa
var f = v => v;
上面的箭头函数等同于:rest
var f = function(v) { return v; };
2.使用注意点code
箭头函数有几个使用注意点。对象
(1)函数体内的this
对象,就是定义时所在的对象,而不是使用时所在的对象。
(2)不能够看成构造函数,也就是说,不能够使用new
命令,不然会抛出一个错误。
(3)不能够使用arguments
对象,该对象在函数体内不存在。若是要用,能够用 rest 参数代替。
(4)不能够使用yield
命令,所以箭头函数不能用做 Generator 函数。
3.this指向区别
箭头函数的this指向定义函数所在的对象;
而普通函数的this指向运行时所在的对象,如
function Timer() { this.s1 = 0; this.s2 = 0; // 箭头函数 setInterval(() => this.s1++, 1000); // 普通函数 setInterval(function () { this.s2++; }, 1000); } var timer = new Timer(); setTimeout(() => console.log('s1: ', timer.s1), 3100); setTimeout(() => console.log('s2: ', timer.s2), 3100); // s1: 3 // s2: 0