【问题标题】:What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?JavaScript 中的 \"=>\"(由等于和大于组成的箭头)是什么意思?
【发布时间】:2022-12-29 15:11:57
【问题描述】:

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

这是代码:

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 或 @987654328 @).箭头函数总是匿名的。这些函数表达式最适合非方法函数,它们不能用作构造函数。

关于 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(45+ 版)
  • Firefox(22+ 版)
  • 边缘(12+ 版)
  • 歌剧(32+ 版)
  • Android 浏览器(47+ 版)
  • Opera Mobile(33+ 版)
  • Android 版 Chrome(47+ 版)
  • 适用于 Android 的 Firefox(44+ 版)
  • Safari(10+ 版)
  • iOS Safari(10.2+ 版)
  • 三星互联网(5+ 版)
  • 百度浏览器 (v. 7.12+)

不支持:

  • IE(通过第 11 节)
  • Opera Mini(通过 v. 8.0)
  • Blackberry 浏览器(至第 10 版)
  • IS Mobile(通过 v11)
  • 适用于 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

另一件很棒的事情是词汇的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's 一个很好的答案什么时候使用箭头函数。

【讨论】:

【解决方案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

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

    与函数表达式相比,箭头函数表达式的语法更短,并且在词法上绑定了 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 所解释的那样,

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

        尽管一个箭头功能可能包含对 super 的引用, 在步骤 4 中创建的函数对象未被制成方法 表演MakeMethod。一个箭头函数引用super 总是包含在一个非箭头功能和必要的 状态实现super可通过访问范围那是 由函数对象捕获箭头功能.

      • 他们是非构造函数。

        这意味着它们没有 [[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 月 13 日,投票最高的答案实际上是错误的。

          =&gt; 的简短版本意味着它是编写函数的快捷方式将其绑定到当前的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 中的含义有关。

          全部函数有一个名为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】:

            使用箭头函数添加简单的 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】:

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

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

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

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

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

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

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

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

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

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

              此“SomeMethod”具有本地“上下文”变量。现在因为“SomeOtherMethod”是从“”SomeMethod”调用的,我们希望它显示“本地上下文”,但它显示“全局上下文”。

              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 上下文的所有场景,以及在哪些场景中不考虑调用者上下文。

              您还可以在this youtube video I made 中看到使用 javascript 的 Arrow 函数的演示,它实际演示了术语上下文。

              【讨论】:

                【解决方案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 没有定义局部绑定争论,极好的,这个, 要么新目标. ArrowFunction 中对 arguments、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值,通常称为语境.
                      • @Bergi 修复了范围
                      猜你喜欢
                      • 2014-09-14
                      • 1970-01-01
                      • 2015-12-28
                      • 2015-10-31
                      • 1970-01-01
                      • 2021-05-10
                      相关资源
                      最近更新 更多