search
HomeWeb Front-endJS TutorialIntroduction to arrow functions in js

Introduction to arrow functions in js

Mar 29, 2018 pm 05:13 PM
javascriptfunctionIntroduction

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 }

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

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 );

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();
  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);  
    }

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();

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; // 或全局对象

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>

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


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

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 {...}

箭头函数没有定义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;  
      }  
    });

使用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

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

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

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

换行

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

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


解析顺序

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

let callback;  
  
callback = callback || function() {}; // ok  
callback = callback || () => {};      // SyntaxError: invalid arrow-function arguments  
callback = callback || (() => {});    // ok
  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 => {  
       // ...  
    });

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
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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.