arrow Function箭头函数
函数的形式:
普通函数 function () {}
箭头函数 (参数) => {函数}形式更简洁
函数表达式:不存在箭头函数声明
var fn = (a,b) => {
return a + b;
}
特殊形式:
1.当参数有且仅有一个,()可以省略
var f1 = (a) => {return a * a};
var f2 = a => {return a * a};
2.当函数体有且仅有一行,{}可以省略,并且会把一行代码的结果返回
var f3 = a => a*a;
注意:当前函数返回的是一个对象的时候,避免歧义加上()
var f4 = val => {
return {name : val}
}
函数体是{},对象也是{},避免歧义
var f5 = val => ({name : val})
固定参数,不定参数:
1.固定参数
var f6 = function (a) {
return function (b) {
return a + b;
}
}
f6(1)(2);//=> 6
2.不定参数
普通函数存在arguments
var f7 = function () {
console.log(arguments);
}
箭头函数中使用不定参数 rest运算,扩展运算符
var f8 = (...arg) => console.log(arg);
arg是个数组,参数形式 a,b,c,d ; console.log(a,b,c,d);
=> 数组[a,b,c,d];
!!扒括号法!!
console.log.apply(console, [1,2,3,4]);//=>1,2,3,4
console.log(...[1,2,3,4]);//=>1,2,3,4
上面的方法经典应用---数组合并:Array.prototype.concat
var arr1 = [1,2,3];
var arr2 = [4,5,6];
var arr = [...arr1, ...arr2];//=>[1,2,3,4,5,6]
好处:
使用简洁的形式,我们不必写一个代码块,只需定义一个表达式,箭头函数就会自动返回它的值:
let sum = (…args) => args.reduce((a, b) => a + b, 0)
通过用括号括起来返回对象文字:
let getObj = () => ({ foo: ‘hello’, bar: ‘world’ })
这种简洁的语法使得箭头函数在定义小而易读的回调时更好
什么情况下不能用构造函数?
(1)构造函数
箭头函数不能作为构造函数,且没有prototype属性(函数层面),但是有“—proto—”(对象层面)
箭头函数表达式的语法比函数表达式更简洁,并且没有自己的this,arguments,super或 new.target。
var Person = name => {
this.name = name;
}
var p = new Person('嘿嘿嘿!报错!');
(2)需要this绑定事件obj
箭头函数里面可以使用this,但是箭头函数中不存在this;
this指向规则:绑定父级作用域中的this
this->window 全局作用域,函数作用域(局部作用域)与箭头函数无关。
var f9 = () => {
console.log(this);
}
f9();//window
f9.call(console);
var obj = {
f1: () => {console.log(this)},
f2: function () {
//this => window
var f = () => console.log(this);
f();
}
}
obj.f1();//window
obj.f2();//obj
var f3 = obj.f2;
f3();//window
obj.f2.call(console);//console
要点:普通函数表达式适合对象方法。箭头函数适合回调或者map、reduce、forEach等方法,不能用于对象方法。
var arr = [1,2,3,4];
var newArr = arr.map((item,index)=>{
return item*2;
})
console.log(newArr);
(3)箭头函数没有arguments
箭头函数没有arguments
var fn7 = () => console.log(arguments);
//=>ReferenceError: arguments is not defined