ES6箭头函数总结
1、箭头函数
let func = (num) => num; let func1 = () => num; let sum = (num1,num2)=> num1+num2; [1,2,3].map(x => x*x)
2、箭头函数特点
(1).箭头函数this为父作用域的this,不是函数调用的this
箭头函数的this永远指向父作用域,call、apply、bind也改变不了。而普通函数的this指向调用它的那个对象。
let person = { age:'22', init:function(){ document.body.onclick() => { alert(this.age); } } } person.init();
例子中,init是function,以person.init()调用,其内部this就是person本身,而onclick回调的是箭头函数,其this就是父作用域的this,即person,因此能够得到age。
let person = { age:'22', init() =>{ document.body.onclick() => { alert(this.age); } } } person.init();
上例中,init为箭头函数,其内部的this为全局的window,onclick的this也就是init函数的this,也是window,因此this.age为undefined。
(2).箭头函数不能作为构造函数,不能使用new
//构造函数如下: function Person(p){ this.name = p.name; } //如果用箭头函数作为构造函数,则如下 var Person = (p) => { this.name = p.name; }
由于this必须是实例化对象,而箭头函数没有实例,此处的this指向别处,不能产生person实例,自相矛盾。
(3).箭头函数没有arguments,caller,callee
箭头函数本身没有arguments,如果箭头函数在一个function内部,它会将外部函数的arguments拿过来用,箭头函数中想要接收不定参数,应该用rest参数...解决。
let B = (b)=> { console.log(arguments) } B(2,3,5,8) //Uncaught ReferenceError: arguments is not defined let C = (...c) => { console.log(c) } C(3,6,94,9) //[3,6,94,9]
(4)箭头函数通过call和apply调用,不会改变this的指向,只会传入参数
let obj2 = { a: 10, b: function(n) { let f = (n) => n + this.a; return f(n); }, c: function(n) { let f = (n) => n + this.a; let m = { a: 20 }; return f.call(m,n); } }; console.log(obj2.b(1)); // 11 console.log(obj2.c(1)); // 11
(5).箭头函数没有原型属性
let a = () => { return 1 } function b() { return 2 } console.log(a.prototype); // undefined console.log(b.prototype); // {constructor: ƒ}
(6).箭头函数不能作为Generator函数,不能使用yield关键字
(7).箭头还是那户返回对象时,要加一个小括号
let func = () => ({foo:1})
(8).箭头函数早Es6 class声明的方法为实例方法,不是原型方法
//deom1 class Super{ sayName(){ //do some thing here } } //通过Super.prototype可以访问到sayName方法,这种形式定义的方法,都是定义在prototype上 var a = new Super() var b = new Super() a.sayName === b.sayName //true //所有实例化之后的对象共享prototypy上的sayName方法 //demo2 class Super{ sayName =()=>{ //do some thing here } } //通过Super.prototype访问不到sayName方法,该方法没有定义在prototype上 var a = new Super() var b = new Super() a.sayName === b.sayName //false //实例化之后的对象各自拥有自己的sayName方法,比demo1需要更多的内存空间
因此,在class中尽量少用箭头函数声明方法。
(9).多重箭头函数是一个高阶函数,相当于内嵌函数
const add = x => y => y + x; //相当于 function add(x){ return function(y){ return y + x; }; }
(10).箭头函数常见错误
let a = { foo: 1, bar: () => console.log(this.foo) } a.bar() //undefined //bar函数中的this指向父作用域,而a对象没有作用域,因此this不是a,打印结果为undefined function A() { this.foo = 1 } A.prototype.bar = () => console.log(this.foo) let a = new A() a.bar() //undefined //原型上使用箭头函数,this指向是其父作用域,并不是对象a,因此得不到预期结果
参考: https://www.cnblogs.com/bfc0517/p/6706498.html
https://www.cnblogs.com/biubiuxixiya/p/8610594.html