IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    一文带你读懂 javascript 中的箭头函数

    风如也发表于 2023-07-18 09:13:31
    love 0

    箭头函数

    箭头函数表达式的语法比函数表达式更简洁,并且没有自己的 this,arguments,super 或 new.target。箭头函数表达式更适用于那些本来需要匿名函数的地方,并且箭头函数不能用作构造函数。

    语法

    (param1, param2, …, paramN) => { statements }
    (param1, param2, …, paramN) => expression
    //相当于:(param1, param2, …, paramN) =>{ return expression; }
    
    // 当只有一个参数时,圆括号是可选的:
    (singleParam) => { statements }
    singleParam => { statements }
    
    // 没有参数的函数应该写成一对圆括号。
    () => { statements }
    
    //加括号的函数体返回对象字面量表达式:
    params => ({foo: bar})
    
    //支持剩余参数和默认参数
    (param1, param2, ...rest) => { statements }
    (param1 = defaultValue1, param2, …, paramN = defaultValueN) => {
    statements }
    
    //同样支持参数列表解构
    let f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
    f();  // 6

    没有单独的this

    箭头函数的作用:更简短的函数且不绑定 this。

    对于普通函数来说,内部的 this 指向函数运行时所在的对象,但是箭头函数不是。

    箭头函数不会创建自己的 this,它只会从自己的作用域链的上一层继承 this。

    箭头函数内部的 this 指向是固定的,普通函数的 this 指向是可变的。

    function foo() {
      setTimeout(() => {
        console.log('id:', this.id);
      }, 100);
    
    }
    
    var id = 21;
    
    foo.call({ id: 42 }); // id: 42

    上面代码中,setTimeout() 的参数是一个箭头函数,这个箭头函数的定义生效是在 foo 函数生成时,而它的真正执行要等到 100 毫秒后。如果是普通函数,执行时 this 应该指向全局对象 window,这时应该输出 21。但是,箭头函数导致 this 总是指向函数定义生效时所在的对象(本例是 {id: 42}),所以打印出来的是 42。

    通过 call 或 apply 或 bind 调用

    由于箭头函数没有自己的 this 指针,通过 call() 或 apply() 方法调用一个箭头函数时,只能传递参数(不能绑定 this),他们的第一个参数会被忽略(这种现象对于 bind 方法同样成立)。

    var adder = {
      base : 1,
    
      add: function(a) {
        var f = v => v + this.base;
        return f(a);
      },
    
      addAnotherThis: function(a) {
        var f = v => v + this.base;
        var b = {
          base : 2
        };
    
        // return f.call(b, a);
        // return f.apply(b, [a]);
        return f.bind(b, a)();
      }
    };
    
    console.log(adder.add(1));         // 输出 2
    console.log(adder.addAnotherThis(1)); // 输出 2

    不绑定 arguments

    箭头函数不绑定 arguments 对象。此外,super,new.target 在箭头函数中也不存在。

    var arguments = [1, 2, 3];
    var fn = () => arguments[0];
    // arguments 只是引用了封闭作用域内的 arguments
    fn(); // 1
    
    function getArgs(n) {
      // 隐式绑定 getArgs 函数的 arguments 对象。arguments[0] 是 n
      // 即传给 getArgs 函数的第一个参数
      var f = () => arguments[0] + n;
      return f();
    }
    
    getArgs(1); // 2
    getArgs(2); // 4
    getArgs(3); // 6
    getArgs(3,2);//6

    在箭头函数中,相比于使用 arguments 对象来说,使用剩余参数是更好的选择。

    function getArgs(n) {
      var f = (...args) => args[0];
      return f();
    }
    
    getArgs(1); // 1
    getArgs(2); // 2
    
    const numbers = (...nums) => nums;

    使用箭头函数作为方法

    箭头函数表达式对非方法函数是最合适的。

    示例1:

    var obj = {
      a: 10,
      b: () => console.log(this.a, this),
      c: function() {
        console.log(this.a, this)
      }
    }
    obj.b();
    // undefined, Window{...}
    obj.c();
    // 10, Object {...}

    示例2:

    let obj = {
      a: 10
    };
    
    Object.defineProperty(obj, "b", {
      get: () => {
        console.log(this.a, typeof this.a, this);
        return this.a + 10;
        // this 代表全局对象 'Window', 因此 'this.a' 返回 'undefined'
      }
    });

    不能使用 new 操作符

    箭头函数不能用作构造器,即不能和 new 一起使用。

    let Apple = () => {}
    let apple = new Apple() // Uncaught TypeError: Apple is not a constructor

    不能使用 prototype 属性

    箭头函数没有 prototype 属性,因为不能用作构造函数。

    let far = function() {}
    console.log(far.prototype) // {constructor: ƒ}
    let Apple = () => {}
    console.log(Apple.prototype) // undefined

    不能用作函数生成器

    函数生成器用作通常不能在箭头函数中使用,除非是嵌套在允许使用的函数内。因此,箭头函数不能用作函数生成器。

    返回对象字面量

    let apple = () => ({ height: 100 })

    箭头函数返回对象字面量,必须用圆括号把对象字面量包起来。

    params => { objectKey: objectValue } 这种语法返回对象是错误的。因为花括号{}里面的代码被解析为一系列语句(代码块),所以如果箭头函数直接返回一个对象,必须在对象外面加上括号。

    换行

    箭头函数中参数和箭头之间不能换行。

    错误方式:

    let apple = () 
    => ({ height: 100 }) // Uncaught SyntaxError: Unexpected token '=>'

    可以在 => 之后换行,或者使用 () 或 {} 换行。

    正确方式:

    let apple = () => 
    ({ height: 100 })
    
    let apple = (
      s, a, b
    ) => 
    ({ height: 100 })
    
    let apple = () => {
      // ...
    }

    箭头函数不适用场合

    定义对象的方法,且方法内部包含 this,不适用箭头函数

    const obj = {
      a: 1,
      fn: () => {
        this.a++
      }
    }
    console.log(obj.fn()) // undefined

    因为对象不构成单独的作用域,导致 fn 箭头函数中定义时的作用域就是全局作用域,fn

    里面的 this 指向全局对象。如果 fn 是普通函数,方法内部的 this 执行调用时的作用域,即obj。

    需要动态 this 的时候,不适用箭头函数

    var button = document.getElementById('press');
    button.addEventListener('click', () => {
      this.classList.toggle('on');
    });

    代码运行时,点击按钮会出现报错,因为 button 的监听函数是一个箭头函数,它的 this 指向全局对象。如果改成普通函数,this 就会动态指向被点击的按钮对象。



沪ICP备19023445号-2号
友情链接