今天主要是学习ES6中函数的扩展。例如常用的箭头函数、函数参数默认值等。
一、箭头函数
ES6可以使用“=>”箭头来定义函数。 我们为什么喜欢使用箭头函数呢,因为它可以简化我们的代码,使之看起来更美观。 如果定义的函数不需要传参则使用空括号来;传一个参数时,可以直接使用这个参数;传参大于一个时,则需要使用括号把参数括起来。
//不传参数var func = () => 1;// 等同于var func= function () { return 1;};//一个参数var func = data => data;// 等同于var func= function (data) { return data;};//两个参数var func = (data,index) => data[index];// 等同于var func= function (data,index) { return data[index];};
如果箭头函数的代码块中的语句大于一条的话,需要用大括号括起来,还要使用return把结果返回。 如果没有用return返回的话,则调用函数结果是undefined
var func = data => { let tempIndex = 2; return data[tempIndex]};
那使用箭头函数需要注意哪些呢?
(1)this指向问题,在箭头函数中this的指向是不变的,就是定义时所在的对象。 (2)不能使用new命令来创建对象。 (3)在函数体内不存在arguments对象,不能使用。可以用 rest 参数代替。 (4)箭头函数不能用作 Generator 函数。
什么时候不能使用箭头函数呢?
(1)定义对象方法
const calculator = { array: [1, 2, 3], sum: () => { //修改 sum(){ console.log(this === window); // => true return this.array.reduce((result, item) => result + item); }};console.log(this === window); // => true// Throws "TypeError: Cannot read property 'reduce' of undefined"//原因是箭头函数把函数上下文绑定到了 window 上calculator.sum();//相同的问题,在定义原型方法也会有function Cat(name) { this.name = name;}Cat.prototype.sayCatName = () => { //修改 function(){ console.log(this === window); // => true return this.name;};const cat = new Cat('Mew');cat.sayCatName(); // => undefined
(2)定义事件回调
//给一个按钮添加点击事件const btn= document.getElementById('Btn');btn.addEventListener('click', () => { //修改 function(){ console.log(this === window); // => true this.innerHTML = '搜索';});//this的指向为window
二、参数默认值
可以给参数默认值,也可结合我们两章学习的解构赋值。 如果函数参数使用了默认值、解构赋值、或者扩展运算符,那么函数内部就不能显式设定为严格模式,否则会报错。
function log(x, y = 5) { console.log(x, y);}log(1) // 1 5log(1, 2) // 1 2function foo({x, y = 5}) { console.log(x, y);}foo({}) // undefined 5foo({x: 1}) // 1 5foo({x: 1, y: 2}) // 1 2foo() // TypeError: Cannot read property 'x' of undefined
三、reset参数
用于获取函数的多余参数。是一个数组,该变量将多余的参数放入数组中。
function add(...values) { let sum = 0; for (var val of values) { sum += val; } return sum;}add(2, 5, 3) // 10
欢迎关注公众号(web学习吧),一起学习进步:
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。