【问题标题】:What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?JavaScript 中的“=>”(由等于和大于组成的箭头)是什么意思?
【发布时间】:2014-09-14 01:41:10
【问题描述】:

我知道>= 运算符的意思是大于或等于,但我在一些源代码中看到过=>。那个运算符是什么意思?

代码如下:

promiseTargetFile(fpParams, aSkipPrompt, relatedURI).then(aDialogAccepted => {
    if (!aDialogAccepted)
        return;

    saveAsType = fpParams.saveAsType;
    file = fpParams.file;

    continueSave();
}).then(null, Components.utils.reportError);

【问题讨论】:

标签: javascript syntax ecmascript-6 arrow-functions


【解决方案1】:

它是什么

这是一个箭头函数。 箭头函数是一种简短的语法,由 ECMAscript 6 引入,可以像使用函数表达式一样使用。换句话说,您可以经常使用它们来代替function (foo) {...} 之类的表达式。但它们有一些重要的区别。例如,它们不绑定自己的 this 值(请参阅下面的讨论)。

箭头函数是 ECMAscript 6 规范的一部分。并非所有浏览器都支持它们,但它们部分或完全支持in Node v. 4.0+ 以及截至 2018 年使用的大多数现代浏览器。(我在下面列出了部分支持的浏览器)。

You can read more in the Mozilla documentation on arrow functions.

来自 Mozilla 文档:

function expressions相比,箭头函数表达式(也称为胖箭头函数)的语法更短,并且在词法上绑定this值(不绑定自己的thisargumentssuper、或new.target)。箭头函数始终是匿名的。这些函数表达式最适合非方法函数,它们不能用作构造函数。

关于 this 如何在箭头函数中工作的说明

箭头函数最方便的功能之一隐藏在上面的文字中:

箭头函数...在词法上绑定this 值(不绑定自己的this...)

这意味着更简单的意思是箭头函数从其上下文中保留this 值,并且没有自己的this。传统函数可能绑定自己的this 值,具体取决于它的定义和调用方式。这可能需要大量的操作,如self = this; 等,才能从另一个函数中的一个函数访问或操作this。有关此主题的更多信息,请参阅the explanation and examples in the Mozilla documentation

示例代码

示例(也来自文档):

var a = [
  "We're up all night 'til the sun",
  "We're up all night to get some",
  "We're up all night for good fun",
  "We're up all night to get lucky"
];

// These two assignments are equivalent:

// Old-school:
var a2 = a.map(function(s){ return s.length });

// ECMAscript 6 using arrow functions
var a3 = a.map( s => s.length );

// both a2 and a3 will be equal to [31, 30, 31, 31]

兼容性说明

您可以在 Node 中使用箭头函数,但浏览器支持参差不齐。

浏览器对此功能的支持已经有了很大的改进,但对于大多数基于浏览器的使用来说,它仍然不够广泛。截至 2017 年 12 月 12 日,当前版本支持:

  • Chrome (v. 45+)
  • Firefox (v. 22+)
  • Edge (v. 12+)
  • 歌剧 (v. 32+)
  • Android 浏览器 (v. 47+)
  • Opera Mobile (v. 33+)
  • Chrome for Android (v. 47+)
  • Firefox for Android (v. 44+)
  • Safari (v. 10+)
  • iOS Safari (v. 10.2+)
  • 三星互联网 (v. 5+)
  • 百度浏览器 (v. 7.12+)

不支持:

  • IE(通过 v. 11)
  • Opera Mini(通过 v. 8.0)
  • 黑莓浏览器(通过第 10 版)
  • IE Mobile(通过第 11 版)
  • 适用于 Android 的 UC 浏览器(通过 v. 11.4)
  • QQ(通过 1.2 版)

您可以在CanIUse.com(无从属关系)找到更多(和更新的)信息。

【讨论】:

  • TypeScript 似乎也支持它。
  • 看起来这是一个 lambda 表达式,是吗?
  • 想提一下浏览器兼容性我使用 ES6/ES7 箭头函数和其他与 IE11 原生不兼容的功能,但我使用 Gulp 或 Webpack 以及 Babel 将 ES6 转换为 ES5,因此它可以在 IE11 中使用.所以如果你需要 IE11 支持并且你不介意设置 Babel,那就去吧。
【解决方案2】:

这被称为箭头函数,是 ECMAScript 2015 spec 的一部分...

var foo = ['a', 'ab', 'abc'];

var bar = foo.map(f => f.length);

console.log(bar); // 1,2,3

比上一个更短的语法:

// < ES6:
var foo = ['a', 'ab', 'abc'];

var bar = foo.map(function(f) {
  return f.length;
});
console.log(bar); // 1,2,3

DEMO

另一个很棒的事情是 lexical this... 通常,你会这样做:

function Foo() {
  this.name = name;
  this.count = 0;
  this.startCounting();
}

Foo.prototype.startCounting = function() {
  var self = this;
  setInterval(function() {
    // this is the Window, not Foo {}, as you might expect
    console.log(this); // [object Window]
    // that's why we reassign this to self before setInterval()
    console.log(self.count);
    self.count++;
  }, 1000)
}

new Foo();

但这可以用这样的箭头重写:

function Foo() {
  this.name = name;
  this.count = 0;
  this.startCounting();
}

Foo.prototype.startCounting = function() {
  setInterval(() => {
    console.log(this); // [object Object]
    console.log(this.count); // 1, 2, 3
    this.count++;
  }, 1000)
}

new Foo();

DEMO

MDN
More on Syntax

更多信息,here'swhen 使用箭头函数的一个很好的答案。

【讨论】:

【解决方案3】:

这些是箭头函数

也称为胖箭头函数。它们是编写函数表达式的简洁明了的方式,例如function() {}.

箭头函数在定义函数时可以消除functionreturn{}的需要。它们是单行的,类似于 Java 或 Python 中的 Lambda 表达式。

无参数示例

const queue = ['Dave', 'Sarah', 'Sharon'];
const nextCustomer = () => queue[0];

console.log(nextCustomer()); // 'Dave'

如果需要在同一个箭头函数中执行多个语句,则需要将queue[0] 包装在大括号{} 中。在这种情况下,return 语句不能省略。

1个参数的例子

const queue = ['Dave', 'Sarah', 'Sharon'];
const addCustomer = name => {
  queue.push(name);
};

addCustomer('Toby');

console.log(queue); // ['Dave', 'Sarah', 'Sharon', 'Toby']

您可以从上面省略{}

当只有一个参数时,参数周围的括号()可以省略。

多参数示例

const addNumbers = (x, y) => x + y

console.log(addNumbers(1, 5)); // 6

一个有用的例子

const fruits = [
    { name: 'Apple', price: 2 },
    { name: 'Bananna', price: 3 },
    { name: 'Pear', price: 1 }
];

如果我们想在单个数组中获取每个水果的价格,在 ES5 中我们可以这样做:

fruits.map(function(fruit) {
    return fruit.price;
}); // [2, 3, 1]

在带有新箭头函数的 ES6 中,我们可以使它更简洁:

fruits.map(fruit => fruit.price); // [2, 3, 1]

关于箭头函数的更多信息可以在here找到。

【讨论】:

    【解决方案4】:

    这将是 ECMAScript 6 中引入的“箭头函数表达式”。

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/arrow_functions

    出于历史目的(如果 wiki 页面稍后更改),它是:

    与函数表达式相比,箭头函数表达式的语法更短,并且在词法上绑定了 this 值。箭头函数始终是匿名的。

    【讨论】:

    • 介意提供足够的信息,这样大多数读者就不必深入研究了吗?
    • 我链接到的 wiki 非常简洁地描述了它的含义:“与函数表达式相比,箭头函数表达式的语法更短,并且在词法上绑定了 this 值。箭头函数始终是匿名的。”
    • 在此处将其添加为报价确实有助于您的回答。
    【解决方案5】:

    只是添加另一个示例,说明 lambda 在不使用 map 的情况下可以做什么:

    a = 10
    b = 2
    
    var mixed = (a,b) => a * b; 
    // OR
    var mixed = (a,b) => { (any logic); return a * b };
    
    console.log(mixed(a,b)) 
    // 20
    

    【讨论】:

      【解决方案6】:

      正如其他人所说,这是一种创建函数的新语法。

      但是,这种功能与普通功能不同:

      • 它们绑定this 值。正如the spec所解释的,

        ArrowFunction 没有为 arguments 定义本地绑定, superthisnew.target。对arguments 的任何引用, ArrowFunction 中的superthisnew.target 必须 解析为词法封闭环境中的绑定。通常 这将是立即封闭的功能环境 功能。

        即使 ArrowFunction 可能包含对 super 的引用, 步骤 4 中创建的函数对象未通过 执行MakeMethod。一个引用 superArrowFunction 总是包含在非ArrowFunction 和必要的 实现super 的状态可通过 scope 访问,即 由ArrowFunction的函数对象捕获。

      • 他们是非构造函数。

        这意味着它们没有 [[Construct]] 内部方法,因此无法实例化,例如

        var f = a => a;
        f(123);  // 123
        new f(); // TypeError: f is not a constructor
        

      【讨论】:

        【解决方案7】:

        我读过,这是ES6Arrow Functions的符号

        这个

        var a2 = a.map(function(s){ return s.length });
        

        使用Arrow Function可以写成

        var a3 = a.map( s => s.length );
        

        MDN Docs

        【讨论】:

          【解决方案8】:

          对其他答案不满意。截至 2019 年 3 月 2013 年投票最高的答案实际上是错误的。

          =&gt; 的简短版本是编写一个函数 AND 将其绑定到当前 this 的快捷方式

          const foo = a => a * 2;
          

          实际上是一个快捷方式

          const foo = function(a) { return a * 2; }.bind(this);
          

          您可以看到所有缩短的内容。我们不需要function,也不需要return,也不需要.bind(this),甚至不需要大括号或圆括号

          箭头函数的一个稍长的例子可能是

          const foo = (width, height) => {
            const area = width * height;
            return area;
          };
          

          表明如果我们想要函数的多个参数,我们需要括号,如果我们想要编写多个表达式,我们需要大括号和显式return

          了解.bind 部分很重要,这是一个很大的话题。它与 this 在 JavaScript 中的含义有关。

          ALL 函数有一个名为 this 的隐式参数。调用函数时如何设置this,取决于该函数的调用方式。

          function foo() { console.log(this); }
          

          如果你正常调用它

          function foo() { console.log(this); }
          foo();
          

          this 将是全局对象。

          如果您处于严格模式

          `use strict`;
          function foo() { console.log(this); }
          foo();
          
          // or
          
          function foo() {
             `use strict`;
             console.log(this);
           }
          foo();
          

          它将是undefined

          您可以直接使用callapply设置this

          function foo(msg) { console.log(msg, this); }
          
          const obj1 = {abc: 123}
          const obj2 = {def: 456}
          
          foo.call(obj1, 'hello');  // prints Hello {abc: 123}
          foo.apply(obj2, ['hi']);  // prints Hi {def: 456}
          

          您也可以使用点运算符. 隐式设置this

          function foo(msg) { console.log(msg, this); }
          const obj = {
             abc: 123,
             bar: foo,
          }
          obj.bar('Hola');  // prints Hola {abc:123, bar: f}
          

          当您想将函数用作回调或侦听器时会出现问题。您创建类并希望分配一个函数作为访问该类实例的回调。

          class ShowName {
            constructor(name, elem) {
              this.name = name;
              elem.addEventListener('click', function() {
                 console.log(this.name);  // won't work
              }); 
            }
          }
          

          上面的代码将不起作用,因为当元素触发事件并调用函数时,this 值将不是类的实例。

          解决该问题的一种常见方法是使用.bind

          class ShowName {
            constructor(name, elem) {
              this.name = name;
              elem.addEventListener('click', function() {
                 console.log(this.name); 
              }.bind(this); // <=========== ADDED! ===========
            }
          }
          

          因为箭头语法和我们写的一样

          class ShowName {
            constructor(name, elem) {
              this.name = name;
              elem.addEventListener('click',() => {
                 console.log(this.name); 
              });
            }
          }
          

          bind 有效地创建了一个新函数。如果bind 不存在,您基本上可以像这样制作自己的

          function bind(functionToBind, valueToUseForThis) {
            return function(...args) {
              functionToBind.call(valueToUseForThis, ...args);
            };
          }
          

          在没有扩展运算符的旧 JavaScript 中,它会是

          function bind(functionToBind, valueToUseForThis) {
            return function() {
              functionToBind.apply(valueToUseForThis, arguments);
            };
          }
          

          了解该代码需要an understanding of closures,但简短版本是bind 会创建一个新函数,该函数始终使用绑定到它的this 值调用原始函数。箭头函数做同样的事情,因为它们是bind(this)的快捷方式

          【讨论】:

            【解决方案9】:

            使用 Arrowfunction 添加简单的 CRUD 示例

             //Arrow Function
             var customers   = [
               {
                 name: 'Dave',
                 contact:'9192631770'
               },
               {
                 name: 'Sarah',
                 contact:'9192631770'
               },
               {
                 name: 'Akhil',
                 contact:'9928462656' 
               }],
            
            // No Param READ
             getFirstCustomer = () => { 
               console.log(this);
               return customers[0];
             };
              console.log("First Customer "+JSON.stringify(getFirstCustomer())); // 'Dave' 
            
               //1 Param SEARCH
              getNthCustomer = index=>{
                if( index>customers.length)
                {
                 return  "No such thing";
               }
               else{
                   return customers[index];
                 } 
              };
              console.log("Nth Customer is " +JSON.stringify(getNthCustomer(1))); 
            
               //2params ADD
              addCustomer = (name, contact)=> customers.push({
                 'name': name,
                 'contact':contact
                });
              addCustomer('Hitesh','8888813275');
              console.log("Added Customer "+JSON.stringify(customers)); 
            
              //2 param UPDATE
              updateCustomerName = (index, newName)=>{customers[index].name= newName};
              updateCustomerName(customers.length-1,"HiteshSahu");
              console.log("Updated Customer "+JSON.stringify(customers));
            
              //1 param DELETE
              removeCustomer = (customerToRemove) => customers.pop(customerToRemove);
              removeCustomer(getFirstCustomer());
              console.log("Removed Customer "+JSON.stringify(customers)); 
            

            【讨论】:

              【解决方案10】:

              用符号 (=>) 表示的箭头函数可帮助您创建匿名函数和方法。这导致更短的语法。例如,下面是一个简单的“加”函数,它返回两个数字相加。

              function Add(num1 , num2 ){
              return num1 + num2;
              }
              

              通过使用“箭头”语法,上述函数变得更短,如下所示。

              上面的代码有两部分如上图所示:-

              Input: — 此部分指定匿名函数的输入参数。

              逻辑: — 这部分出现在符号“=>”之后。这部分有实际功能的逻辑。

              许多开发人员认为箭头函数可以让您的语法更短、更简单,从而使您的代码具有可读性。

              如果你相信上面这句话,那么让我向你保证,这是一个神话。如果你认为一个正确编写的函数名称比使用箭头符号在一行中创建的神秘函数更具可读性。

              箭头函数的主要用途是保证代码在 调用者上下文。

              参见下面的代码,其中定义了一个全局变量“context”,这个全局变量是在一个函数“SomeOtherMethod”中访问的,该函数是从其他方法“SomeMethod”调用的。

              此“SomeMethod”具有本地“上下文”变量。现在因为从 ""SomeMethod" 调用 "SomeOtherMethod" 我们希望它显示 "local context" ,但它显示 "global context"。

              var context = “global context”;
              
              function SomeOtherMethod(){
              alert(this.context);
              }
              
              function SomeMethod(){
              this.context = “local context”;
              SomeOtherMethod();
              }
              
              var instance = new SomeMethod();
              

              但是如果使用箭头函数替换调用,它将显示“本地上下文”。

              var context = "global context";
              
                  function SomeMethod(){
                      this.context = "local context";
                      SomeOtherMethod = () => {
                          alert(this.context);
                      }
                      SomeOtherMethod();
                  }
                  var instance = new SomeMethod();
              

              我鼓励您阅读此链接 (Arrow function in JavaScript),该链接解释了 javascript 上下文的所有场景以及不尊重调用者上下文的场景。

              您还可以看到Arrow function with javascript in this youtube video 的演示,它实际上演示了上下文一词。

              【讨论】:

                【解决方案11】:

                正如所有其他答案已经说过的,它是 ES2015 箭头函数语法的一部分。更具体地说,它不是运算符,而是将参数与正文分开的标点符号:ArrowFunction : ArrowParameters =&gt; ConciseBody。例如。 (params) =&gt; { /* body */ }.

                【讨论】:

                  【解决方案12】:

                  正如其他人所说,常规(传统)函数使用调用函数的对象中的this(例如,被点击的按钮)。相反,箭头函数使用定义函数的对象中的this

                  考虑两个几乎相同的函数:

                  regular = function() {
                    ' Identical Part Here;
                  }
                  
                  
                  arrow = () => {
                    ' Identical Part Here;
                  }
                  

                  下面的 sn-p 演示了 this 代表每个函数的根本区别。 正则函数输出[object HTMLButtonElement],而箭头函数输出[object Window]

                  <html>
                   <button id="btn1">Regular: `this` comes from "this button"</button>
                   <br><br>
                   <button id="btn2">Arrow: `this` comes from object that defines the function</button>
                   <p id="res"/>
                  
                   <script>
                    regular = function() {
                      document.getElementById("res").innerHTML = this;
                    }
                  
                    arrow = () => {
                      document.getElementById("res").innerHTML = this;
                    }
                  
                    document.getElementById("btn1").addEventListener("click", regular);
                    document.getElementById("btn2").addEventListener("click", arrow);
                   </script>
                  </html>

                  【讨论】:

                    【解决方案13】:

                    ES6箭头函数:

                    在 javascript 中,=&gt; 是箭头函数表达式的符号。箭头函数表达式没有自己的this 绑定,因此不能用作构造函数。例如:

                    var words = 'hi from outside object';
                    
                    let obj = {
                      words: 'hi from inside object',
                      talk1: () => {console.log(this.words)},
                      talk2: function () {console.log(this.words)}
                    }
                    
                    obj.talk1();  // doesn't have its own this binding, this === window
                    obj.talk2();  // does have its own this binding, this is obj

                    箭头函数使用规则:

                    • 如果有恰好一个参数,您可以省略参数的括号。
                    • 如果您返回一个表达式并在同一行执行此操作,您可以省略 {}return 语句

                    例如:

                    let times2 = val => val * 2;  
                    // It is on the same line and returns an expression therefore the {} are ommited and the expression returns implictly
                    // there also is only one argument, therefore the parentheses around the argument are omitted
                    
                    console.log(times2(3));

                    【讨论】:

                      【解决方案14】:

                      JavaScript 箭头函数大致相当于 python 中的 lambda 函数或 Ruby 中的块。 这些是匿名函数,具有自己的特殊语法并在其封闭范围的上下文中运行。这意味着他们没有自己的“this”,而是从直接封闭的函数中访问。

                      来自ECMA standard

                      ArrowFunction 没有为 参数 定义本地绑定, superthisnew.target。在 ArrowFunction 中对参数、super、this 或 new.target 的任何引用都必须解析为 在词法封闭的环境中绑定。通常这将是 直接封闭函数的函数环境。

                      通常您可以阅读“箭头函数表达式是传统函数表达式的紧凑替代方案”,这是不正确的。 箭头函数不是传统函数的简写,它们的行为与传统函数不同。

                      语法

                      // Traditional Function
                      // Create their own scope inside the function
                      function (a){
                        return a + 100;
                      }
                      
                      // Arrow Function 
                      // Do NOT create their own scope
                      // (Each step along the way is a valid "arrow function")
                      
                      // 1. Remove the word "function" and place arrow between the argument and opening body bracket
                      (a) => {
                        return a + 100;
                      }
                      
                      // 2. Remove the body braces and word "return" -- the return is implied.
                      (a) => a + 100;
                      
                      // 3. Remove the argument parentheses (only valid with exactly one argument)
                      a => a + 100;
                      

                      【讨论】:

                      • JS 中没有函数具有“固定数量的参数”
                      • @Bergi 是的,你说得对。我想说“一种接受参数的语法”,但这具有误导性。我认为现在使用代码 sn-p 可以自我解释。
                      • 顺便说一句,他们也有自己的(变量)范围。它们没有单独的 this 值,通常称为 context
                      • @Bergi 修复了范围
                      猜你喜欢
                      • 2022-12-29
                      • 1970-01-01
                      • 2015-12-28
                      • 2015-10-31
                      • 1970-01-01
                      • 2021-05-10
                      相关资源
                      最近更新 更多