• es6箭头函数中return的用法


    箭头函数

    一.箭头函数

    1.箭头函数没有this
    箭头左边是输入参数,右边是输出参数。

    console.log(this) //window
    默认的this是window
    
    let fn=()=>console.log(this)
    fn() //window
    外面的this是什么它就是什么
    
    fn.call({name:'jack'}) //window
    就算指定this也无效,this还是window
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    不管你对箭头函数做任何的call、bind操作都无效。
    this永远都是最开始定义时获取的this。

    箭头函数的this就是普通变量
    箭头函数里的this就是外面的this(默认的window),箭头函数没有this。
    所以你加call、bind没用。

    上级对象时this永远都是指向window,只有是非箭头函数时才是上级的this
    箭头函数所在的this 是它外面的那个非箭头函数的this。
    this指向外层函数作用域(不是外层对象哦)。

    var obj = {
      i: 10,
      b: () => console.log(this.i, this),
      c: function() {
        console.log(this.i, this);
      }
    }
    obj.b(); //undefined, Window
    obj.c(); //10, Object
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    2.箭头函数没有arguments
    在这里插入图片描述

    二.箭头函数中return的用法

    (a, b) => a + b;
         a => a + 100;
       (a) => { return a + 100; }
         a => a + 100;
    
    let f1 = (x,y) => ({name:x,age:y}) 
    f1() //{name:x,age:y}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    1.当有多个参数没有参数时,需要加()
    2.如果箭头函数的代码块部分多于一条语句,就要使用大括号将它们括起来,并且使用return关键字返回。

    const foo = (a, b) => { a+b; }
    foo(1, 2) //undefined
    
    const foo1 = (a, b) => { return a+b; }
    foo1(1, 2) //3
    
    • 1
    • 2
    • 3
    • 4
    • 5

    3.凡是用大括号括起来的部分如果想拿到返回值就必须用return关键字返回,否则返回undefined
    如果箭头函数只有一行语句,可以省略大括号、return关键字

    const foo = (a, b) => a+b 
    //const foo = (a, b) => { return a+b }
    foo(1, 2) // 3
    
    • 1
    • 2
    • 3

    4.如果要返回一个对象字面量表达式,需要在表达式两边加上括号
    括号内表示是一个整体,直接返回对象会出错,必须加个括号

    let f1 = (x,y) => ({name:x,age:y}) 
    f1() //{name:x,age:y}
    
    • 1
    • 2
  • 相关阅读:
    Java命令模式源码剖析及使用场景
    mongodb的认识
    【Android 标题文字居中 快速实现】
    小学生python游戏编程arcade----坦克大战3
    【备忘录】修复docker环境下的nacos安全漏洞:身份认证绕过漏洞
    阿里云国际站如何助力餐饮行业出海?
    关于ssh的使用
    基于flask部署paddleocr
    HTML静态网页作业——我的家乡安庆
    Python青少年等级考试实操题(二级)
  • 原文地址:https://blog.csdn.net/baidulixueqin/article/details/125490542