• 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
  • 相关阅读:
    【Qt】控件探幽——QLineEdit
    【基本数据结构】平衡二叉树
    Linux多线程C++版(八) 线程同步方式-----条件变量
    [附源码]java毕业设计构建养猪场管理系统
    Hadoop3教程(三十三):(生产调优篇)慢磁盘监控与小文件归档
    c++运算符重载的几个例子记录
    Linux: 如何命令行安装R包
    《MySQL高级篇》十六、主从复制
    吴恩达老师机器学习课程笔记 06 逻辑回归
    【代数学习题4.2】从零理解范数与迹 —— 求数域元素的范数与迹
  • 原文地址:https://blog.csdn.net/baidulixueqin/article/details/125490542