Table of Contents
Shorter functions
Do not bind this
Relationship with strict mode
Use call or apply to call
Do not bind arguments
Use arrow functions like methods
使用yield关键字
返回对象字面量
Home Web Front-end JS Tutorial Introduction to arrow functions in js

Introduction to arrow functions in js

Mar 29, 2018 pm 05:13 PM
javascript function Introduction

The arrow function is a shorthand function expression, and it has the this value of the lexical scope (that is, it will not create new objects such as this, arguments, super and new.target in its own scope). Additionally, arrow functions are always anonymous.

Basic Grammar

  1. (param1, param2, …, paramN) => { statements }  
    (param1, param2, …, paramN) => expression  
             // equivalent to:  => { return expression; }  
      
    // 如果只有一个参数,圆括号是可选的:  
    (singleParam) => { statements }  
    singleParam => { statements }  
      
    // 无参数的函数需要使用圆括号:  
    () => { statements }
    Copy after login

Advanced Grammar

  1. // 返回对象字面量时应当用圆括号将其包起来:  
    params => ({foo: bar})  
      
    // 支持 Rest parameters 和 default parameters:  
    (param1, param2, ...rest) => { statements }  
    (param1 = defaultValue1, param2, …, paramN = defaultValueN) => { statements }  
      
    // Destructuring within the parameter list is also supported  
    var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;  
    f();  // 6
    Copy after login

Description


The introduction of arrow functions has two impacts: one is shorter function writing, and the other is lexical analysis of this.

Shorter functions

In some functional programming patterns, shorter functions are very popular. Try to compare:

  1. var a = [  
      "Hydrogen",  
      "Helium",  
      "Lithium",  
      "Beryl­lium"  
    ];  
      
    var a2 = a.map(function(s){ return s.length });  
      
    var a3 = a.map( s => s.length );
    Copy after login

Do not bind this

Before the arrow function, each newly defined function had its own this Value (for example, the this of a constructor points to a new object; the this value of a function in strict mode is undefined; if a function is called as a method of an object, its this points to the object that called it). In object-oriented programming, this can prove to be very annoying.

function Person() {  
  // 构造函数 Person() 定义的 `this` 就是新实例对象自己  
  this.age = 0;  
  setInterval(function growUp() {  
    // 在非严格模式下,growUp() 函数定义了其内部的 `this`  
    // 为全局对象, 不同于构造函数Person()的定义的 `this`  
    this.age++;   
  }, 1000);  
}  
  
var p = new Person();
Copy after login
  1. In ECMAScript 3/5, this problem can be solved by adding a variable to point to the desired this object, and then placing the variable in the closure.

  2. function Person() {  
      var self = this; // 也有人选择使用 `that` 而非 `self`.   
                       // 只要保证一致就好.  
      self.age = 0;  
      
      setInterval(function growUp() {  
        // 回调里面的 `self` 变量就指向了期望的那个对象了  
        self.age++;  
      }, 1000);  
    }
    Copy after login

In addition, you can also use the bind function to pass the expected this value to the growUp() function.

The arrow function will capture the this value of its context as its own this value, so the following code will run as expected.

  1. function Person(){  
      this.age = 0;  
      
      setInterval(() => {  
        this.age++; // |this| 正确地指向了 person 对象  
      }, 1000);  
    }  
      
    var p = new Person();
    Copy after login

Relationship with strict mode

Considering that this is at the lexical level, all rules related to this in strict mode will be neglect.

  1. var f = () => {'use strict'; return this};  
    f() === window; // 或全局对象
    Copy after login

Other rules of strict mode remain unchanged.

Use call or apply to call

Since this is already in the lexical The binding is completed at the level. When calling a function through the call() or apply() method, only the parameters are passed in, and it has no impact on this:

  1. <span style="font-size:14px;">var adder = {  
      base : 1,  
          
      add : function(a) {  
        var f = v => v + this.base;  
        return f(a);  
      },  
      
      addThruCall: function(a) {  
        var f = v => v + this.base;  
        var b = {  
          base : 2  
        };  
                  
        return f.call(b, a);  
      }  
    };  
      
    console.log(adder.add(1));         // 输出 2  
    console.log(adder.addThruCall(1)); // 仍然输出 2(而不是3 ——译者注)</span>
    Copy after login

Do not bind arguments

The arrow function will not expose the arguments object inside it: arguments.length, arguments[0], arguments[1], etc., will not point to the arguments of the arrow function. Instead, it points to a value named arguments in the scope where the arrow function is located (if any, otherwise, it is undefined).

  1. var arguments = 42;  
    var arr = () => arguments;  
      
    arr(); // 42  
      
    function foo() {  
      var f = () => arguments[0]; // foo&#39;s implicit arguments binding  
      return f(2);  
    }  
      
    foo(1); // 1
    Copy after login


The arrow function does not have its own arguments object, but in most cases, the rest parameter can give a solution:

  1. function foo() {   
      var f = (...args) => args[0];   
      return f(2);   
    }  
      
    foo(1); // 2
    Copy after login

Use arrow functions like methods

As mentioned above, arrow function expressions are most appropriate for functions without method names. Let’s see What happens when we try to use them as methods.

  1. &#39;use strict&#39;;  
    var obj = {  
      i: 10,  
      b: () => console.log(this.i, this),  
      c: function() {  
        console.log( this.i, this)  
      }  
    }  
    obj.b(); // prints undefined, Window  
    obj.c(); // prints 10, Object {...}
    Copy after login

箭头函数没有定义this绑定。

  1. &#39;use strict&#39;;  
    var obj = {  
      a: 10  
    };  
      
    Object.defineProperty(obj, "b", {  
      get: () => {  
        console.log(this.a, typeof this.a, this);  
        return this.a+10; // represents global object &#39;Window&#39;, therefore &#39;this.a&#39; returns &#39;undefined&#39;  
      }  
    });
    Copy after login

使用new操作符

箭头函数不能用作构造器,和 new 一起用就会抛出错误。

使用yield关键字

yield关键字通常不能在箭头函数中使用(except when permitted within functions further nested within it)。因此,箭头函数不能用作Generator函数。

返回对象字面量

请牢记,用 params => {object:literal} 这种简单的语法返回一个对象字面量是行不通的:

  1. var func = () => {  foo: 1  };  
    // Calling func() returns undefined!  
      
    var func = () => {  foo: function() {}  };  
    // SyntaxError: function statement requires a name
    Copy after login

这是因为花括号(即 {} )里面的代码被解析为声明序列了(例如, foo 被认为是一个 label, 而非对象字面量里的键)。

所以,记得用圆括号把对象字面量包起来:

  1. var func = () => ({ foo: 1 });
    Copy after login

换行

箭头函数在参数和箭头之间不能换行哦

  1. var func = ()  
               => 1; // SyntaxError: expected expression, got &#39;=>&#39;
    Copy after login


解析顺序

在箭头函数中的箭头不是操作符(或者运算符,就像'+ -'那些), 但是 箭头函数有特殊的解析规则就是:相比普通的函数, 随着操作符优先级不同交互也不同(建议看英文版)。

let callback;  
  
callback = callback || function() {}; // ok  
callback = callback || () => {};      // SyntaxError: invalid arrow-function arguments  
callback = callback || (() => {});    // ok
Copy after login
  1. 示例

  2. // 一个空箭头函数,返回 undefined  
    let empty = () => {};  
      
    (() => "foobar")() // 返回 "foobar"   
      
    var simple = a => a > 15 ? 15 : a;   
    simple(16); // 15  
    simple(10); // 10  
      
    let max = (a, b) => a > b ? a : b;  
      
    // Easy array filtering, mapping, ...  
      
    var arr = [5, 6, 13, 0, 1, 18, 23];  
    var sum = arr.reduce((a, b) => a + b);  // 66  
    var even = arr.filter(v => v % 2 == 0); // [6, 0, 18]  
    var double = arr.map(v => v * 2);       // [10, 12, 26, 0, 2, 36, 46]  
      
    // 更多简明的promise链  
    promise.then(a => {  
      // ...  
    }).then(b => {  
       // ...  
    });
    Copy after login

The above is the detailed content of Introduction to arrow functions in js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

Considerations for parameter order in C++ function naming Considerations for parameter order in C++ function naming Apr 24, 2024 pm 04:21 PM

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

How to write efficient and maintainable functions in Java? How to write efficient and maintainable functions in Java? Apr 24, 2024 am 11:33 AM

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Apr 21, 2024 am 10:21 AM

The advantages of default parameters in C++ functions include simplifying calls, enhancing readability, and avoiding errors. The disadvantages are limited flexibility and naming restrictions. Advantages of variadic parameters include unlimited flexibility and dynamic binding. Disadvantages include greater complexity, implicit type conversions, and difficulty in debugging.

What are the benefits of C++ functions returning reference types? What are the benefits of C++ functions returning reference types? Apr 20, 2024 pm 09:12 PM

The benefits of functions returning reference types in C++ include: Performance improvements: Passing by reference avoids object copying, thus saving memory and time. Direct modification: The caller can directly modify the returned reference object without reassigning it. Code simplicity: Passing by reference simplifies the code and requires no additional assignment operations.

What is the difference between custom PHP functions and predefined functions? What is the difference between custom PHP functions and predefined functions? Apr 22, 2024 pm 02:21 PM

The difference between custom PHP functions and predefined functions is: Scope: Custom functions are limited to the scope of their definition, while predefined functions are accessible throughout the script. How to define: Custom functions are defined using the function keyword, while predefined functions are defined by the PHP kernel. Parameter passing: Custom functions receive parameters, while predefined functions may not require parameters. Extensibility: Custom functions can be created as needed, while predefined functions are built-in and cannot be modified.

C++ Function Exception Advanced: Customized Error Handling C++ Function Exception Advanced: Customized Error Handling May 01, 2024 pm 06:39 PM

Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.

See all articles