ES6箭头函数与普通函数的区别

箭头函数:

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: ƒ}

箭头函数不能当做Generator函数,不能使用yield关键字

点赞
收藏

评论区

加载中...

相关推荐

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

JS难点:this 指向

原文链接:this指向分为两种情况,一种是普通函数中使用的this,另外一种是箭头函数中的this。普通函数this指向调用者。场景1javascriptfunctionsayHi()console.log(this)sayHi()//window这里的t

ES6新增内容(部分)

ES6新增内容(部分)一、两个声明变量的方法let、constlet:不能重复声明、有暂时性死区,不能提前访问、{}块级作用域。const:声明常量、声明之后不能被修改。二、箭头函数语法:(参数){表达式}箭头函数中this没有固定指向,一般指向宿主对象。

ES6箭头函数特点

1、语法简单constfunx1;constfun()1;constfun(x,y){1;returnxy;}2、内置return语句、单行代码返回当前代码的返回值、多行时返回undefined3、自动绑定this、this为上级的作用域

ES6 箭头函数

一、在es6中函数的定义和es5之间有明显区别。不需要关键字function来进行定义,使用来指向函数。不可以new也就是做构造函数以及没有arguments参数。箭头函数的this是在定义的时候确定指向这和es5不一样,es5是谁调用他,他就指向谁。1document.addEventListene

ES6特性总结(3)——函数的变化

前言es6中的一系列关于函数用法的变化是非常有趣的,在es6的新标准下,你可以更加轻便地使用函数,并且可以仿照面向对象编程的思想来使用函数,将函数转化为“类”。(这里的类加了引号,原因我们会在后面的学习中解释)下面就让我们来一起看一看es6下的函数有哪些有趣的变化。1.箭头函数箭头函数是es6下实现的一种新的函数书写方法。在过去的