Basic Summary of Arrow Functions in JavaScript


foreword

Some small summary of arrow functions


1. Arrow function features

Arrow Function (the arrow function is a new function in the ES6 standard

/**
 * ES6箭头函数语法定义函数,
 * 将原函数的“function”关键字和函数名都删掉,
 * 并使用“=>”连接参数列表和函数体。
 *  注意点:{
 * 
 *  如果形参只有一个,则小括号可以省略;
    函数体如果只有一条语句,则花括号可以省略,并省略return,函数的返回值为该条语句的执行结果;
    箭头函数 this 指向声明时所在作用域下 this 的值;
    箭头函数不能作为构造函数实例化;
    不能使用 arguments
}
  如 let sum = (num1, num2) => num1 + num2; 
    // 等同于 let sum = function(num1, num2) { return num1 + num2; }; 
 */

2. Points to note about arrow functions

1.this points to the problem

  • For the function defined by function, the point of this changes with the change of the calling environment.
  • The this point in the arrow function is fixed, always pointing to the environment where the function is defined.
    • In a function defined using function
    • The this pointing changes as the calling environment changes:
 // 普通函数的this指向是随着调用环境的变化而变化的;
      function f1() {
    
    
        console.log("普通函数f1的this:" + this);
      }
      var obj = {
    
     A: f1 };
      f1(); //this指向Window
      obj.A(); //this指向的是 obj { A: foo }

 // 明显使用箭头函数的时候,this的指向是没有发生变化的(这里一直都是window)。
      var f2 = () => {
    
    
        console.log("箭头函数f2的this:" + this);
      };
      var obj2 = {
    
     B: f2 };
      f2();//this指向Window
      obj2.B();//this指向Window

2. Unable to perform constructor

  • Function can define constructors, but arrow functions cannot.
  • Continuing the example from the previous section:
// 对普通函数构造函数
      var f11 = new f1();
      console.log("我是普通函数的构造函数:" + f11);
// 对箭头函数构造函数
      var f21 = new f2();
      console.log("我是箭头函数的构造函数:" + f21);
  • The result display:
    insert image description here

3. Variable promotion

  • Due to the memory mechanism of js, function has the highest level, and when defining functions with arrow functions, the
    keyword var (not to mention when defining let const) is required
  • The variable defined by var cannot be promoted, so the arrow function must be defined before the call
  • Therefore, the arrow function should be defined with var as much as possible and defined before calling

Third, the use of arrow functions

  • Delete the "function" keyword and the function name of the original function, and use "=>" to connect the parameter list and the function body.
  • On the premise of multiple parameters, () cannot be omitted
  • Can be omitted if it is a single parameter
  • If there are no parameters use empty parentheses () instead

1. Arrow functions with multiple parameters

//有多个参数的前提下,()不能省略 若没有参数使用空括号代替
var add = (a, b) => console.log(a + b);
add(1, 2);
//相当于
var function add(a, b) {
    
     console.log(a + b) }
add(1, 2);

2. Single parameter or no parameter

//若为单个参数则可以省略,
// 当函数参数只有一个,括号可以省略;但是没有参数时,括号不可以省略。
var f1 = () =>
{
    
    
  console.log("无参数的时候不能省略括号");
};
f1();
// 单个参数
var f3 = (a) => console.log("单个参数可以省略括号");
f3();

3. Variable parameters

// 可变参数
var f4 = (a, b, c, ...args) => console.log(...args);
f4(1, 2, 3, 4, 5, 6, 7); //console.log(...args)不打印前面的a,b,c

4. The case of omitting return

  • Arrow functions are equivalent to anonymous functions and simplify function definitions.
  • Arrow functions have two formats, one contains only one expression, omitting { ... } and return.
  • There is another one that can contain multiple statements. At this time, { ... } and return cannot be omitted, regardless of the number of parameters
//多条语句,不能省略{ }
var f5 = (a) =>
{
    
    
  a = a + 1;
  return a;
};
console.log(f5(1));
  • If an object is returned
  • Special attention needs to be paid, if it is a single expression to return a custom object,
  • An error will be reported if you do not write parentheses, because there is a syntax conflict with { ... } in the function body.
  • Note that curly braces enclosed in parentheses are object definitions, not function bodies
//如下所示
x => {
    
    key: x} // 报错
x => ({
    
    key: x}) // 正确

Additional points:

补充点

  • The arrow function completely fixes the pointing of this, which always points to the lexical scope, which is the outer caller Person
  • Since this has been bound according to the lexical scope in the arrow function,
    this cannot be bound when calling the arrow function with call() or apply(), that is, the first parameter passed in is ignored
var person = {
    
    
 firstName: "zwt",
 lastName: "cherish",
 getFullName: function ()
 {
    
    
   console.log(this);
   var first = this.firstName;
   console.log(first);
   var fn = () =>
   {
    
    
     console.log(this);
     return this.firstName + this.lastName;
   };
   return fn();
 },
};
person.getFullName();

Summarize

A little summary about arrow functions.

Guess you like

Origin blog.csdn.net/CherishTaoTao/article/details/125817478