箭头函数:
1let fun = () => { 2 console.log('lala'); 3}
普通函数
1function fun() { 2 console.log('lalla'); 3}
箭头函数相当于匿名函数,并且简化了函数定义。箭头函数有两种格式,一种只包含一个表达式,连{ ... }和return都省略掉了。还有一种可以包含多条语句,这时候就不能省略{ ... }和return。
箭头函数是匿名函数,不能作为构造函数,不能使用new
1let FunConstructor = () => { 2 console.log('lll'); 3} 4 5let fc = new FunConstructor();
**结果:**报错 Uncaught TypeError: FunConstructor is not a consructor
箭头函数不绑定arguments,取而代之用rest参数...解决
1//普通函数 2function A(a){ 3 console.log(arguments); 4} 5A(1,2,3,4,5,8); // [1, 2, 3, 4, 5, 8, callee: ƒ, Symbol(Symbol.iterator): ƒ] 6 7//箭头函数 8let C = (...c) => { 9 console.log(c); 10} 11C(3,82,32,11323); // [3, 82, 32, 11323] 12 13function fun1(...theArgs) { 14 console.log(theArgs.length); 15} 16fun1(); // 0 17fun1(5); // 1 18fun1(5, 6, 7); // 3
箭头函数不绑定this,会捕获其所在的上下文的this值,作为自己的this值
1//例一: 2var obj = { 3 a: 10, 4 b: () => { 5 console.log(this.a); // undefined 6 console.log(this); // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …} 7 }, 8 c: function() { 9 console.log(this.a); // 10 10 console.log(this); // {a: 10, b: ƒ, c: ƒ} 11 } 12} 13obj.b(); 14obj.c(); 15 16//例二: 17var obj = { 18 a: 10, 19 b: function(){ 20 console.log(this.a); //10 21 }, 22 c: function() { 23 return ()=>{ 24 console.log(this.a); //10 25 } 26 } 27} 28obj.b(); 29obj.c()();
箭头函数通过call()或apply()方法调用一个函数时,只传入了一个参数,对 this 并没有影响。
箭头函数的 this 永远指向其上下文的 this,任何方法都改变不了其指向,如 call() , bind() , apply()
1let obj2 = { 2 a: 10, 3 b: function(n) { 4 let f = (n) => n + this.a; 5 return f(n); 6 }, 7 c: function(n) { 8 let f = (n) => n + this.a; 9 let m = { 10 a: 20 11 }; 12 return f.call(m,n); 13 } 14}; 15console.log(obj2.b(1)); // 11 16console.log(obj2.c(1)); // 11
箭头函数没有原型属性
1var a = ()=>{ 2 return 1; 3} 4 5function b(){ 6 return 2; 7} 8 9console.log(a.prototype); // undefined 10console.log(b.prototype); // {constructor: ƒ}