493

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

这是代码:

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

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

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

14 回答 14

606

这是什么

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

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

您可以在Mozilla 文档中阅读有关箭头功能的更多信息。

来自 Mozilla 文档:

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

this关于箭头函数如何工作的注释

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

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

简而言之,这意味着箭头函数保留this其上下文中的值,并且没有自己的this. 一个传统的函数可能会绑定它自己的this值,这取决于它是如何定义和调用的。这可能需要大量的体操,例如self = this;等,才能this从另一个函数中的一个函数访问或操作。有关此主题的更多信息,请参阅Mozilla 文档中的说明和示例

示例代码

示例(也来自文档):

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 日,它在以下版本中受支持:

  • 铬 (v. 45+)
  • 火狐 (v. 22+)
  • 边缘 (v. 12+)
  • 歌剧 (v. 32+)
  • Android 浏览器 (v. 47+)
  • Opera 移动版 (v. 33+)
  • 适用于 Android 的 Chrome (v. 47+)
  • Firefox for Android (v. 44+)
  • Safari (v. 10+)
  • iOS Safari (v. 10.2+)
  • 三星互联网 (v. 5+)
  • 百度浏览器 (v. 7.12+)

不支持:

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

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

于 2014-07-23T02:32:55.223 回答
85

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

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

演示

另一个很棒的事情是词汇 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();

演示

MDN
更多关于语法

更多信息,这里是关于何时使用箭头函数的一个很好的答案。

于 2014-07-23T02:35:11.517 回答
29

这些是箭头函数

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

箭头函数可以在定义函数时消除function,return和的需要。{}它们是单行的,类似于 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]

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

于 2017-04-26T09:15:13.227 回答
26

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

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

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

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

于 2014-07-23T02:32:22.930 回答
21

只是添加另一个示例,说明 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
于 2014-07-23T03:14:55.637 回答
14

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

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

  • 它们绑定this值。正如规范所解释的

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

    即使ArrowFunction可能包含对 的引用super,在步骤 4 中创建的函数对象也不会通过执行MakeMethod变成方法。引用的ArrowFunctionsuper 始终包含在非ArrowFunctionsuper中,并且可以通过ArrowFunction的函数对象捕获的范围访问实现的必要状态。

  • 他们是非构造函数。

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

    var f = a => a;
    f(123);  // 123
    new f(); // TypeError: f is not a constructor
    
于 2015-10-11T22:48:25.523 回答
8

我读过,这是Arrow Functionsin的象征ES6

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

使用Arrow Function可以写成

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

MDN 文档

于 2014-07-23T02:33:05.683 回答
8

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

简而言之,=>是编写函数并将其绑定到当前函数的快捷方式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部分很重要,这是一个很大的话题。它与thisJavaScript 中的含义有关。

所有函数都有一个名为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

您可以this直接使用call或设置apply

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

理解该代码需要理解闭包,但简短的版本是创建一个新函数,该函数始终使用绑定到它bind的值调用原始函数。this箭头函数做同样的事情,因为它们是bind(this)

于 2019-03-13T04:11:36.657 回答
6

使用 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)); 
于 2017-11-02T09:40:51.757 回答
3

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

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

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

在此处输入图像描述

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

输入: — 本节指定匿名函数的输入参数。

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

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

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

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

请参阅下面的代码,其中定义了全局变量“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();

我鼓励您阅读此链接(JavaScript 中的箭头函数),它解释了 javascript 上下文的所有场景以及在哪些场景中调用者上下文不受尊重。

您还可以在这个 youtube 视频中看到使用 javascript 的箭头函数的演示,该视频实际上演示了术语 Context。

于 2019-02-10T01:11:07.443 回答
2

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

于 2015-09-30T12:48:19.907 回答
2

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

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

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


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

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>

于 2019-09-17T01:59:11.223 回答
1

ES6箭头功能:

在 javascript 中,=>是箭头函数表达式的符号。箭头函数表达式没有自己的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

使用箭头函数的规则:

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

例如:

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

于 2018-08-29T08:24:21.697 回答
1

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

ECMA标准

ArrowFunction 不为argumentssuperthisnew.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;
于 2021-07-22T14:42:36.750 回答